Skip to content

Commit abd87e3

Browse files
jonahbronPaul Sokolovskystlehmann
committed
logging: Introduced a supplemental logging rotating handler package
Co-authored-by: Paul Sokolovsky <[email protected]> Co-authored-by: Stefan Lehmann <[email protected]>
1 parent d97b821 commit abd87e3

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

Diff for: python-stdlib/logging-rotating-handler/README.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Rotating File Logging Handler
2+
3+
Add-on package for [`logging`](../logging/). Provides a Handler that can rotate
4+
logging output between multiple files while keeping the total filesize below a
5+
specified limit.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import os
2+
from . import Handler
3+
4+
# Source: https://github.com/pfalcon/pycopy-lib/blob/master/logging/logging/handlers.py
5+
6+
7+
def try_remove(fn: str) -> None:
8+
"""Try to remove a file if it existst."""
9+
try:
10+
os.remove(fn)
11+
except OSError:
12+
pass
13+
14+
15+
def get_filesize(fn: str) -> int:
16+
"""Return size of a file."""
17+
return os.stat(fn)[6]
18+
19+
20+
class RotatingFileHandler(Handler):
21+
"""A rotating file handler like RotatingFileHandler.
22+
23+
Compatible with CPythons `logging.handlers.RotatingFileHandler` class.
24+
"""
25+
26+
def __init__(self, filename, maxBytes=0, backupCount=0):
27+
super().__init__()
28+
self.filename = filename
29+
self.maxBytes = maxBytes
30+
self.backupCount = backupCount
31+
32+
try:
33+
self._counter = get_filesize(self.filename)
34+
except OSError:
35+
self._counter = 0
36+
37+
def emit(self, record):
38+
"""Write to file."""
39+
msg = self.formatter.format(record)
40+
s_len = len(msg)
41+
42+
if self.maxBytes and self.backupCount and self._counter + s_len > self.maxBytes:
43+
# remove the last backup file if it is there
44+
try_remove(self.filename + ".{0}".format(self.backupCount))
45+
46+
for i in range(self.backupCount - 1, 0, -1):
47+
if i < self.backupCount:
48+
try:
49+
os.rename(
50+
self.filename + ".{0}".format(i),
51+
self.filename + ".{0}".format(i + 1),
52+
)
53+
except OSError:
54+
pass
55+
56+
try:
57+
os.rename(self.filename, self.filename + ".1")
58+
except OSError:
59+
pass
60+
self._counter = 0
61+
62+
with open(self.filename, "a") as f:
63+
f.write(msg + "\n")
64+
65+
self._counter += s_len

Diff for: python-stdlib/logging-rotating-handler/manifest.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
metadata(
2+
version="0.7.5",
3+
author="Stefan Lehmann, Paul Sokolovsky",
4+
description="Rotating file handler for the logging package",
5+
)
6+
7+
require("logging")
8+
9+
package("logging")

0 commit comments

Comments
 (0)