comparison mercurial/loggingutil.py @ 40821:96be0ecad648

loggingutil: add basic logger backends These classes will be used in command server. They are similar to the blackboxlogger, but it can't be factored out since the blackbox is so tightly coupled with a repo object.
author Yuya Nishihara <yuya@tcha.org>
date Sun, 18 Nov 2018 18:58:06 +0900
parents 698477777883
children 2372284d9457
comparison
equal deleted inserted replaced
40819:cb372d09d30a 40821:96be0ecad648
10 10
11 import errno 11 import errno
12 12
13 from . import ( 13 from . import (
14 pycompat, 14 pycompat,
15 )
16
17 from .utils import (
18 dateutil,
19 procutil,
20 stringutil,
15 ) 21 )
16 22
17 def openlogfile(ui, vfs, name, maxfiles=0, maxsize=0): 23 def openlogfile(ui, vfs, name, maxfiles=0, maxsize=0):
18 """Open log file in append mode, with optional rotation 24 """Open log file in append mode, with optional rotation
19 25
47 newpath='%s.%d' % (path, i)) 53 newpath='%s.%d' % (path, i))
48 rotate(oldpath=path, 54 rotate(oldpath=path,
49 newpath=maxfiles > 0 and path + '.1') 55 newpath=maxfiles > 0 and path + '.1')
50 return vfs(name, 'a', makeparentdirs=False) 56 return vfs(name, 'a', makeparentdirs=False)
51 57
58 def _formatlogline(msg):
59 date = dateutil.datestr(format=b'%Y/%m/%d %H:%M:%S')
60 pid = procutil.getpid()
61 return b'%s (%d)> %s' % (date, pid, msg)
62
63 def _matchevent(event, tracked):
64 return b'*' in tracked or event in tracked
65
66 class filelogger(object):
67 """Basic logger backed by physical file with optional rotation"""
68
69 def __init__(self, vfs, name, tracked, maxfiles=0, maxsize=0):
70 self._vfs = vfs
71 self._name = name
72 self._trackedevents = set(tracked)
73 self._maxfiles = maxfiles
74 self._maxsize = maxsize
75
76 def tracked(self, event):
77 return _matchevent(event, self._trackedevents)
78
79 def log(self, ui, event, msg, opts):
80 line = _formatlogline(msg)
81 try:
82 with openlogfile(ui, self._vfs, self._name,
83 maxfiles=self._maxfiles,
84 maxsize=self._maxsize) as fp:
85 fp.write(line)
86 except IOError as err:
87 ui.debug(b'cannot write to %s: %s\n'
88 % (self._name, stringutil.forcebytestr(err)))
89
90 class fileobjectlogger(object):
91 """Basic logger backed by file-like object"""
92
93 def __init__(self, fp, tracked):
94 self._fp = fp
95 self._trackedevents = set(tracked)
96
97 def tracked(self, event):
98 return _matchevent(event, self._trackedevents)
99
100 def log(self, ui, event, msg, opts):
101 line = _formatlogline(msg)
102 try:
103 self._fp.write(line)
104 self._fp.flush()
105 except IOError as err:
106 ui.debug(b'cannot write to %s: %s\n'
107 % (stringutil.forcebytestr(self._fp.name),
108 stringutil.forcebytestr(err)))
109
52 class proxylogger(object): 110 class proxylogger(object):
53 """Forward log events to another logger to be set later""" 111 """Forward log events to another logger to be set later"""
54 112
55 def __init__(self): 113 def __init__(self):
56 self.logger = None 114 self.logger = None