Use logger. ~
To log to a file and print ()
to log to the console.
Have you ever thought it was a hassle?
When making a tool in the company, I want to output the log to both the console and the file, and if I was examining the logging module, if I use both StreamHandler
which outputs the log to the console and FileHandler
which outputs to the file, the console output I found that both and file output can be done easily, so I will leave a memorandum at that time.
-Please stop printing and import logging for log output -Python Official Reference (logging)
If you want to output to either a file or console with logging.basicConfig ()
, you can specify filename =
or stream =
, but if you want to output to both a file and a console, etc. When using more than one, give a list of handlers to handlers =
without specifying and initialize.
If the file handler specifies a folder that does not exist in the save path, an error will occur, so if it does not exist, add the process to create it.
import os
import sys
from datetime import datetime
import logging
from logging import StreamHandler, FileHandler, Formatter
from logging import INFO, DEBUG, NOTSET
#Stream handler settings
stream_handler = StreamHandler()
stream_handler.setLevel(INFO)
stream_handler.setFormatter(Formatter("%(message)s"))
#Check if there is a save destination
if not os.path.isdir('./Log'):
os.makedirs('./Log', exist_ok=True)
#File handler settings
file_handler = FileHandler(
f"./Log/log{datetime.now():%Y%m%d%H%M%S}.log"
)
file_handler.setLevel(DEBUG)
file_handler.setFormatter(
Formatter("%(asctime)s@ %(name)s [%(levelname)s] %(funcName)s: %(message)s")
)
#Root logger settings
logging.basicConfig(level=NOTSET, handlers=[stream_handler, file_handler])
You are now set to output the logging module to both the console and the file.
Note the output level set with logging.basicConfig ()
. Logs are passed in the order of root logger → handler. Therefore, if you set the output level to INFO
etc. in the root logger settinglogging.basicConfig ()
, the log with the output level DEBUG
will be played at the time of the root logger. Therefore, even if the output level is set to DEBUG
in the file handler settings, the log with the output level DEBUG
is not saved in the file.
The program is written in solid here, but I think it's a good idea to put it in a function as appropriate. Because there is no other place to use these objects.
If you want to use a logger, use logging.getLogger (__ name__)
to get the logger object and use it.
Also, even if you cross functions or files, once you set the root logger, you can use it anywhere, so you can use it by calling logging.getLogger (__name__)
at the place you want to use.
logger = logging.getLogger(__name__)
logger.debug("debug")
logger.info("info")
logger.warn("warn")
logger.error("error")
logger.critical("critical")
I think that all the logs are output to the file and the logs from info are output to the console.
Then use rich to make the console output rich. The method is simple, just change logging.StreamHandler
to rich.logging.RichHandler
.
Install rich.
$ pip install rich
Once installed, replace StreamHandler
in the logger setup chapter with RichHandler
.
from rich.logging import RichHandler
#Stream handler settings
rich_handler: RichHandler = RichHandler(rich_tracebacks=True)
rich_handler.setLevel(INFO)
rich_handler.setFormatter(Formatter("%(message)s"))
#File handler settings
#abridgement
#Root logger settings
logging.basicConfig(level=NOTSET, handlers=[rich_handler, file_handler])
The output is now rich.
Recommended Posts