tcp - ぶやかー

loggerを使う

debugなどでprintするならlogger使った方が最終的にメリットが多い。
が、毎回フォーマットとか考えるのは面倒。

classのinitにデフォルトで仕込むとか、共通モジュール化しておく。

from logging import StreamHandler, Formatter, getLogger, INFO, DEBUG


class SomeClass():
    def __init__(self):
        self.loop = asyncio.get_event_loop()
        self.running = True

        stream_handler = StreamHandler()
        stream_handler.setLevel(DEBUG)
        stream_handler.setFormatter(
            Formatter("%(asctime)s [%(threadName)s,%(thread)d][%(processName)s,%(process)d][%(module)s,%(funcName)s,%(lineno)d] %(message)s"))
        self.logger = getLogger()
        self.logger.setLevel(DEBUG)
        self.logger.addHandler(stream_handler)

とりあえず使う(Minimum)

フォーマットとか後で考える場合も最低3行でlogger設定しておく。
// getLoggerなくてもいけるけど、後々いい感じにするとかもできるので。

import logging
logger = logging.getLogger()
logging.basicConfig(level=logging.INFO)

logger.info('some info')
logger.debug('some debug message')

タイムスタンプなどもつけるなら

import logging

logger = logging.getLogger()
logging.basicConfig(format='%(asctime)s %(levelname)s [%(module)s,%(funcName)s,%(lineno)d] %(message)s', level=logging.INFO)

Stack Traceが拾える

logger.exception()でStack Traceが拾える。exc_info=Trueでも同じことができるが、logger.exception()で使い分けたほうがわかりやすい。

import logging

logger = logging.getLogger()
logging.basicConfig(format='%(asctime)s %(levelname)s [%(module)s,%(funcName)s,%(lineno)d] %(message)s', level=logging.INFO)

try:
    (777/0)
except Exception as e:
    print('=== logger.exception ===')
    logger.exception(f'{e}')
    print('=== exc_info option===')
    logger.error(f'{e}', exc_info=True)

nameが使える

loggerの名前には__name__が使えるのでモジュール事にいい感じにカテゴライズできる

logger = logging.getLogger(__name__)

pprint的に出力する

思ってたのと違うが少しは見やすくできる。

import logging
from pprint import pformat

logger = logging.getLogger()
logging.basicConfig(format='%(asctime)s %(levelname)s [%(module)s,%(funcName)s,%(lineno)d] %(message)s', level=logging.DEBUG)


msg = [
    {
        'params': {
            'user': 'hoge',
            'data': {
                'Humpty': 'Dumpty'
            }
        }
    },
    {
        'params': {
            'user': 'fuga',
            'data': {
                'Kesaran': 'Pasaran'
            }
        }
    }
]

## そのまま出力
logging.debug(msg)

## pformatで出力
logging.debug(pformat(msg))

## タイムスタンプとか考慮した場合1行づつ出力
for line in pformat(msg).split('\n'):
    logger.debug(line)

この記事を書いた人 Wrote this article

kmatsunuma

TOP