I'm trying to do a test run of the logging
module's RotatingFileHandler
as follows:
import logging
from logging.handlers import RotatingFileHandler
# logging.basicConfig(filename="example.log", level=logging.DEBUG)
logger = logging.getLogger('my_logger')
handler = RotatingFileHandler("my_log.log", maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.debug("Hello, world!")
However, with logging.basicConfig
line commented out, the resulting my_log.log
file contains no data:
If I comment in the line with logging.basicConfig(filename="example.log", level=logging.DEBUG)
, I get the expected my_log.log
files with numbered suffixes. However, there is also the example.log
which is a (relatively) large file:
How can I set up the logging so that it only generates the my_log.log
files, and not the large example.log
file?
I found that to obtain the desired behavior one has to use the same name in the
basicConfig
andRotatingFileHandler
initializations:Here, I have chose the same name
my_log.log
. This results in only the 'size-limited' logs being created:All previous answers are correct, here another way of doing the same thing except we use logging config file instead.
logging_config.ini
Here is the config file :
myScrypt.py
here is simple logging script that uses the above config file
RESULT
here is the result, notice maxBytes is set to 10 but in real life, that's clearly too small. (args=('testing.log','a',10,100)
Python provides 5 logging levels out of the box (in increasing order of severity):
DEBUG
,INFO
,WARNING
,ERROR
andCRITICAL
. The default one isWARNING
. The docs says, thatSo if you use
.debug
with the default settings, you won't see anything in your logs.The easiest fix would be to use
logger.warning
function rather thatlogger.debug
:And if you want to change logger level you can use
.setLevel
method: