LoginSignup
5
3

More than 5 years have passed since last update.

loggingで直近n件のログを取得

Last updated at Posted at 2018-04-23

動機

エラーが起こった地点からn件をメールで送信したかった

コード・使い方

使い方は普通のloggingと同じです。
handler = StackHandler(max=10)でハンドラをつくり、
設定したハンドラのstackを見に行けばテキストのリストが入っています。
maxにはスタックする数の最大を入れます。(任意)

stacklog.py
import logging
from collections import deque

class StackHandler(logging.StreamHandler):
    def __init__(self, max=10):
        super(StackHandler,self).__init__()
        self.stack = deque(maxlen=max)

    def emit(self, record):
        self.stack.append(self.format(record))

logger = logging.getLogger()
handler = StackHandler(max=10)
handler.setFormatter(logging.Formatter("%(levelname)-8s %(asctime)s %(message)s"))
logger.addHandler(handler)

for i in range(20):
    logger.error(i)

for i in handler.stack:
    print (i)
出力
ERROR    2018-04-23 13:23:38,966 10
ERROR    2018-04-23 13:23:38,966 11
ERROR    2018-04-23 13:23:38,966 12
ERROR    2018-04-23 13:23:38,966 13
ERROR    2018-04-23 13:23:38,966 14
ERROR    2018-04-23 13:23:38,966 15
ERROR    2018-04-23 13:23:38,966 16
ERROR    2018-04-23 13:23:38,966 17
ERROR    2018-04-23 13:23:38,966 18
ERROR    2018-04-23 13:23:38,966 19
5
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3