StreamHandler
: console, FileHandler
: fileIf you want to set it to Japan time, you need to mess with the Formatter.converter
attribute.
Since Formatter.converter
is a callable that returns time.struct_time
, define such an appropriate function.
def customTime(*args):
return datetime.now(timezone('Asia/Tokyo')).timetuple()
.timetuple ()
, please comment.main.py
import logging
from pytz import timezone
from datetime import datetime
#Name it logger.By calling with this name, the following settings will be inherited by other modules..
logger = logging.getLogger("example")
logger.setLevel(logging.DEBUG)
#Handler settings to output to console
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
def customTime(*args):
return datetime.now(timezone('Asia/Tokyo')).timetuple()
formatter = logging.Formatter(
fmt='%(levelname)s : %(asctime)s : %(message)s',
datefmt="%Y-%m-%d %H:%M:%S %z"
)
formatter.converter = customTime
sh.setFormatter(formatter)
#Setting the handler to output to a file
fh = logging.FileHandler("logs/example.log")
fh.setLevel(logging.DEBUG)
def customTime(*args):
return datetime.now(timezone('Asia/Tokyo')).timetuple()
formatter = logging.Formatter(
fmt='%(levelname)s : %(asctime)s : %(message)s',
datefmt="%Y-%m-%d %H:%M:%S %z"
)
formatter.converter = customTime
fh.setFormatter(formatter)
logger.addHandler(sh)
logger.addHandler(fh)
Recommended Posts