]> git.phdru.name Git - m_lib.git/blob - m_lib/flog.py
b46bae59833b809b686c87ed839a1e152d768a6e
[m_lib.git] / m_lib / flog.py
1 #! /usr/bin/env python
2 """File logger
3
4    Written by Broytman, Dec 1997. Copyright (C) 1997 PhiloSoft Design.
5 """
6
7
8 from time import *
9
10
11 class FLog:
12    def __init__(self, f, overwrite = 0, timeformat = "%a %d %b %Y %T"):
13       if type(f) == type(''): # If f is string - use it as file's name
14          if overwrite:
15             mode = 'w'
16          else:
17             mode = 'a'
18          self.outfile = open(f, mode)
19       else:
20          self.outfile = f     # else assume it is opened file (fileobject) or
21                               # "compatible" object (must has write() method)
22       self.f = f
23       self.timeformat = timeformat
24
25
26    def __del__(self):
27       self.close()
28
29
30    def close(self):
31       if type(self.f) == type(''): # If f was opened - close it
32          self.outfile.close()
33
34
35    def log(self, str):
36       self.outfile.write("%s %s\n" % (strftime(self.timeformat, localtime(time())), str))
37
38
39    __call__ = log
40
41
42    def flush(self):
43       self.outfile.flush()
44
45
46 def makelog(f):
47    return FLog(f, 1)
48
49
50 def openlog(f):
51    return FLog(f)
52
53
54 def test():
55    log = makelog("test.log")
56    log.log("Log opened")
57    log("Log closed")
58    log.close()
59
60 if __name__ == "__main__":
61    test()