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