Example 1: Logging FileHandler() and logging StreamHandler()
import logging
import os
#path acquisition
root = os.path.dirname(os.path.realpath(__file__))
# log_path = os.path.join(root, "example.log")
# name = "example.log"
debug = False
# when debug is true, show DEBUG and INFO in screen
# when debug is false, show DEBUG in file and info in both screen&file
# INFO will always be in screen
# create a logger
logger = logging.getLogger() # logging.FileHandler set the file location and file name again at ()
# critical > error > warning > info > debug > notset
logger.setLevel(logging.DEBUG) # level=logging.DEBUG indicate all >= DEBUG this level all will be output
# define the formate
formatter = logging.Formatter('%(asctime)s: %(message)s', "%Y-%m-%d %H:%M")
# create another handler for output log to console
console_handler = logging.StreamHandler()
if debug:
console_handler.setLevel(logging.DEBUG)
else:
console_handler.setLevel(logging.INFO)
# create a handler for write log to file
logfile = os.path.join(root, 'run.log')
print('Creat Log File in: ', logfile)
file_handler = logging.FileHandler(logfile, mode='w')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# add Handler to logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
# test
logger.debug('this is a {} debug message'.format(1))
logger.info('this is an info message')
logger.debug('this is a debug message')
logger.info('this is an info message')
logger.debug('this is a debug message')
logger.info('this is an info message')
Function: It is faster to understand the code directly. The above code mainly implements: simultaneously output log content in the console and log files, and output logs according to different log levels. If the debug is False, only debug level logs will be output in the console, and debug and info level logs will be output in the log file; If the debug is true, both the console and log files will output logs at the debug and info levels. Therefore, if you want the console output to be consistent with the log file output, you can set debug. PS: Careful review of the code comments makes it easy to understand. .
Code run result: .
Console:

Log file:

Encapsulated version: .
#Logger.py.
import os
import logging
from datetime import datetime
def get_logger(root, name=None, debug=True):
# when debug is true, show DEBUG and INFO in screen
# when debug is false, show DEBUG in file and info in both screen&file
# INFO will always be in screen
# create a logger
logger = logging.getLogger(name)
# critical > error > warning > info > debug > notset
logger.setLevel(logging.DEBUG)
# define the formate
formatter = logging.Formatter('%(asctime)s: %(message)s', "%Y-%m-%d %H:%M")
# create another handler for output log to console
console_handler = logging.StreamHandler()
if debug:
console_handler.setLevel(logging.DEBUG)
else:
console_handler.setLevel(logging.INFO)
# create a handler for write log to file
logfile = os.path.join(root, 'run.log')
print('Creat Log File in: ', logfile)
file_handler = logging.FileHandler(logfile, mode='w')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# add Handler to logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
return logger
#Mian.py.
import os
import logger
root = os.path.dirname(os.path.realpath(__file__))
dataset = "log"
log_path = os.path.join(root, dataset)
if not os.path.isdir(log_path):
os.makedirs(log_path, exist_ok=True)
logger = logger.get_logger(log_path,'run.txt')
logger.debug("this is test")
Example 2: Simple version
from loguru import logger
logger.add("log/file_{time}.log", level="TRACE", rotation="100 MB")
logger.info("test")
Result:
console

log file.

Reference:
Loguru. logger - loguru documentation.