@@ -1982,26 +1982,47 @@ Using a rotator and namer to customize log rotation processing
1982
1982
--------------------------------------------------------------
1983
1983
1984
1984
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
1986
1992
1987
1993
def namer(name):
1988
1994
return name + ".gz"
1989
1995
1990
1996
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)
1996
2000
os.remove(source)
1997
2001
1998
- rh = logging.handlers.RotatingFileHandler(...)
2002
+
2003
+ rh = logging.handlers.RotatingFileHandler('rotated.log', maxBytes=128, backupCount=5)
1999
2004
rh.rotator = rotator
2000
2005
rh.namer = namer
2001
2006
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
2005
2026
2006
2027
A more elaborate multiprocessing example
2007
2028
----------------------------------------
0 commit comments