diff 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
line wrap: on
line diff
--- a/mercurial/loggingutil.py	Tue Dec 04 17:13:01 2018 -0500
+++ b/mercurial/loggingutil.py	Sun Nov 18 18:58:06 2018 +0900
@@ -14,6 +14,12 @@
     pycompat,
 )
 
+from .utils import (
+    dateutil,
+    procutil,
+    stringutil,
+)
+
 def openlogfile(ui, vfs, name, maxfiles=0, maxsize=0):
     """Open log file in append mode, with optional rotation
 
@@ -49,6 +55,58 @@
                        newpath=maxfiles > 0 and path + '.1')
     return vfs(name, 'a', makeparentdirs=False)
 
+def _formatlogline(msg):
+    date = dateutil.datestr(format=b'%Y/%m/%d %H:%M:%S')
+    pid = procutil.getpid()
+    return b'%s (%d)> %s' % (date, pid, msg)
+
+def _matchevent(event, tracked):
+    return b'*' in tracked or event in tracked
+
+class filelogger(object):
+    """Basic logger backed by physical file with optional rotation"""
+
+    def __init__(self, vfs, name, tracked, maxfiles=0, maxsize=0):
+        self._vfs = vfs
+        self._name = name
+        self._trackedevents = set(tracked)
+        self._maxfiles = maxfiles
+        self._maxsize = maxsize
+
+    def tracked(self, event):
+        return _matchevent(event, self._trackedevents)
+
+    def log(self, ui, event, msg, opts):
+        line = _formatlogline(msg)
+        try:
+            with openlogfile(ui, self._vfs, self._name,
+                             maxfiles=self._maxfiles,
+                             maxsize=self._maxsize) as fp:
+                fp.write(line)
+        except IOError as err:
+            ui.debug(b'cannot write to %s: %s\n'
+                     % (self._name, stringutil.forcebytestr(err)))
+
+class fileobjectlogger(object):
+    """Basic logger backed by file-like object"""
+
+    def __init__(self, fp, tracked):
+        self._fp = fp
+        self._trackedevents = set(tracked)
+
+    def tracked(self, event):
+        return _matchevent(event, self._trackedevents)
+
+    def log(self, ui, event, msg, opts):
+        line = _formatlogline(msg)
+        try:
+            self._fp.write(line)
+            self._fp.flush()
+        except IOError as err:
+            ui.debug(b'cannot write to %s: %s\n'
+                     % (stringutil.forcebytestr(self._fp.name),
+                        stringutil.forcebytestr(err)))
+
 class proxylogger(object):
     """Forward log events to another logger to be set later"""