forked from pfalcon/pycopy-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.py
61 lines (46 loc) · 1.67 KB
/
handlers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import os
import sys
from loggingpycom import Handler
def try_remove(fn: str) -> None:
"""Try to remove a file if it existst."""
try:
os.remove(fn)
except OSError:
pass
def get_filesize(fn: str) -> int:
"""Return size of a file."""
return os.stat(fn)[6]
class RotatingFileHandler(Handler):
"""A rotating file handler like RotatingFileHandler.
Compatible with CPythons `logging.handlers.RotatingFileHandler` class.
"""
def __init__(self, filename, maxBytes=0, backupCount=0):
super().__init__()
self.filename = filename
self.maxBytes = maxBytes
self.backupCount = backupCount
try:
self._counter = get_filesize(self.filename)
except OSError:
self._counter = 0
def emit(self, record):
"""Write to file."""
msg = self.formatter.format(record)
s_len = len(msg)
if self.maxBytes and self.backupCount and self._counter + s_len > self.maxBytes:
# remove the last backup file if it is there
try_remove(self.filename + ".{0}".format(self.backupCount))
for i in range(self.backupCount - 1, 0, -1):
if i < self.backupCount:
try:
os.rename(
self.filename + ".{0}".format(i),
self.filename + ".{0}".format(i + 1),
)
except OSError:
pass
os.rename(self.filename, self.filename + ".1")
self._counter = 0
with open(self.filename, "a") as f:
f.write(msg + "\n")
self._counter += s_len