LoginSignup
4
7

More than 5 years have passed since last update.

Bottleのアクセスログ記録

Last updated at Posted at 2018-02-09

Pythonの軽量Webフレームワークにおいて、標準出力に表示されるアクセスログをログファイルへ記録するやり方を公開します。

logging.conf
[loggers]
keys=root

[handlers]
keys=fileRotatingHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=fileRotatingHandler

[handler_fileRotatingHandler]
class=logging.handlers.TimedRotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=('./log/application.log', 'd', 1, 10)

[formatter_simpleFormatter]
format=%(asctime)s: %(threadName)s: %(levelname)s: %(name)s: %(message)s
datefmt=
sever.py
from bottle import Bottle, request, response
from functools import wraps
import logging                            # ログ記録
import logging.config                     # ログコンフィグ

# -------------------------------------------------
# ロギング設定
# -------------------------------------------------
logging.config.fileConfig('./conf/logging.conf')
logger = logging.getLogger(__name__)

# -------------------------------------------------
# デコレータ
# -------------------------------------------------
# アクセスログ取得用(デコレータ関数)
def log_to_logger(fn):
    @wraps(fn)
    def _log_to_logger(*args, **kwargs):
        actual_response = fn(*args, **kwargs)
        # modify this to log exactly what you need:
        logging.info('ACCESSLOG: %s %s %s %s' % (request.remote_addr,
                                        request.method,
                                        # request.url,
                                        request.urlparts.path,
                                        response.status))
        return actual_response
    return _log_to_logger

# デコレータ関数の拡張
app = Bottle()
app.install(log_to_logger)

# -------------------------------------------------
# ルーティング
# -------------------------------------------------
@app.route('/')
def home():
    return ['hello, world']

# quiet=Trueでサイレントモード
app.run(host='0.0.0.0', port='8081', quiet=True)

上記コードを実行すると以下のような結果となります。

$ python3 sever.py &
$ tail -f log/application.log
YYYY-MM-DD HH:MM:SS,ddd: MainThread: INFO: root: ACCESSLOG: xxx.xxx.xxx.xxx GET / 200 OK
4
7
0

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
4
7