Skip to content

Commit 8cdbc46

Browse files
galqiwivsajip
andauthored
Provided better example for logging cookbook (GH-101164)
Co-authored-by: Vinay Sajip <[email protected]>
1 parent 3fa8fe7 commit 8cdbc46

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

Doc/howto/logging-cookbook.rst

+31-10
Original file line numberDiff line numberDiff line change
@@ -1982,26 +1982,47 @@ Using a rotator and namer to customize log rotation processing
19821982
--------------------------------------------------------------
19831983

19841984
An example of how you can define a namer and rotator is given in the following
1985-
snippet, which shows zlib-based compression of the log file::
1985+
runnable script, which shows gzip compression of the log file::
1986+
1987+
import gzip
1988+
import logging
1989+
import logging.handlers
1990+
import os
1991+
import shutil
19861992

19871993
def namer(name):
19881994
return name + ".gz"
19891995

19901996
def rotator(source, dest):
1991-
with open(source, "rb") as sf:
1992-
data = sf.read()
1993-
compressed = zlib.compress(data, 9)
1994-
with open(dest, "wb") as df:
1995-
df.write(compressed)
1997+
with open(source, 'rb') as f_in:
1998+
with gzip.open(dest, 'wb') as f_out:
1999+
shutil.copyfileobj(f_in, f_out)
19962000
os.remove(source)
19972001

1998-
rh = logging.handlers.RotatingFileHandler(...)
2002+
2003+
rh = logging.handlers.RotatingFileHandler('rotated.log', maxBytes=128, backupCount=5)
19992004
rh.rotator = rotator
20002005
rh.namer = namer
20012006

2002-
These are not "true" .gz files, as they are bare compressed data, with no
2003-
"container" such as you’d find in an actual gzip file. This snippet is just
2004-
for illustration purposes.
2007+
root = logging.getLogger()
2008+
root.setLevel(logging.INFO)
2009+
root.addHandler(rh)
2010+
f = logging.Formatter('%(asctime)s %(message)s')
2011+
rh.setFormatter(f)
2012+
for i in range(1000):
2013+
root.info(f'Message no. {i + 1}')
2014+
2015+
After running this, you will see six new files, five of which are compressed:
2016+
2017+
.. code-block:: shell-session
2018+
2019+
$ ls rotated.log*
2020+
rotated.log rotated.log.2.gz rotated.log.4.gz
2021+
rotated.log.1.gz rotated.log.3.gz rotated.log.5.gz
2022+
$ zcat rotated.log.1.gz
2023+
2023-01-20 02:28:17,767 Message no. 996
2024+
2023-01-20 02:28:17,767 Message no. 997
2025+
2023-01-20 02:28:17,767 Message no. 998
20052026
20062027
A more elaborate multiprocessing example
20072028
----------------------------------------

0 commit comments

Comments
 (0)