Python Logging

Logger setting procedure

  1. Give it a name that will be used throughout the application.
  2. Set the handler.
  3. (Filter settings).
  4. Formatter settings.

handler

Formatter

About time format

If 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()

Setting Example

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

Python Logging
Python
Logging properly in Python
I implemented Python Logging
Python --Quick start of logging
kafka python
Python basics ⑤
python + lottery 6
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
[Python] Variables
Python functions
Python sys.intern ()
Python decimals
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Python basics ③
Python basics
[Scraping] Python scraping
Python update (2.6-> 2.7)
Python memorandum
python learning
Hannari Python 2020
python memorandum
Download python
python memorandum
Python memo
started python
Python #JSON
python quiz
Python note
Python string
Python installation
ufo-> python (2)