PythonでSysLogHandlerを使ってsyslogでログを出力する

## 概要
Pythonのログをsyslogに渡して、logrotate.dでローテートしたい。

## 関連記事
- [Railsのログをsyslogに出す](https://qiita.com/Esfahan/items/9763e0bc509f75b9d379)
- [任意のログをlogrotateを使って管理する](https://qiita.com/Esfahan/items/a8058f1eb593170855a1)


## rsyslogの設定
/etc/rsyslog.confを以下のように編集。

```diff
# rsyslog configuration file

# For more information see /usr/share/doc/rsyslog-*/rsyslog_conf.html
# If you experience problems, see http://www.rsyslog.com/doc/troubleshoot.html

#### MODULES ####

# The imjournal module bellow is now used as a message source instead of imuxsock.
$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imjournal # provides access to the systemd journal
#$ModLoad imklog # reads kernel messages (the same are read from journald)
#$ModLoad immark  # provides --MARK-- message capability

# Provides UDP syslog reception
# syslog が UDP で転送されてくるので、それを受信できるようにする。
-#$ModLoad imudp
-#$UDPServerRun 514
+$ModLoad imudp
+$UDPServerRun 514

# Provides TCP syslog reception
#$ModLoad imtcp
#$InputTCPServerRun 514


#### GLOBAL DIRECTIVES ####

# Where to place auxiliary files
$WorkDirectory /var/lib/rsyslog

# Use default timestamp format
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

# File syncing capability is disabled by default. This feature is usually not required,
# not useful and an extreme performance hit
#$ActionFileEnableSync on

# Include all config files in /etc/rsyslog.d/
$IncludeConfig /etc/rsyslog.d/*.conf

# Turn off message reception via local log socket;
# local messages are retrieved through imjournal now.
$OmitLocalLogging on

# File to store the position in the journal
$IMJournalStateFile imjournal.state


#### RULES ####

# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.*                                                 /dev/console

# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none                /var/log/messages

# The authpriv file has restricted access.
authpriv.*                                              /var/log/secure

# Log all the mail messages in one place.
mail.*                                                  -/var/log/maillog


# Log cron stuff
cron.*                                                  /var/log/cron

# Everybody gets emergency messages
*.emerg                                                 :omusrmsg:*

# Save news errors of level crit and higher in a special file.
uucp,news.crit                                          /var/log/spooler

# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log


# ### begin forwarding rule ###
# The statement between the begin ... end define a SINGLE forwarding
# rule. They belong together, do NOT split them. If you create multiple
# forwarding rules, duplicate the whole block!
# Remote Logging (we use TCP for reliable delivery)
#
# An on-disk queue is created for this action. If the remote host is
# down, messages are spooled to disk and sent when it is up again.
#$ActionQueueFileName fwdRule1 # unique name prefix for spool files
#$ActionQueueMaxDiskSpace 1g   # 1gb space limit (use as much as possible)
#$ActionQueueSaveOnShutdown on # save messages to disk on shutdown
#$ActionQueueType LinkedList   # run asynchronously
#$ActionResumeRetryCount -1    # infinite retries if host is down
# remote host is: name/ip:port, e.g. 192.168.0.1:514, port optional
#*.* @@remote-host:514
# ### end of the forwarding rule ###

+!python
+# 全てのログを記録
+*.*  /var/log/python-sample/production-all.log
+# notice以上のログを記録
+*.notice  /var/log/python-sample/production-notice.log
+# errのみを記録（crit, alertなどは記録されない）
+*.=err  /var/log/python-sample/production-err.log
+# noticeとerrの2つを記録
+*.=notice;*.=err  /var/log/python-sample/production-notice-err.log
```

## ログレベル
ログのプライオリティ一覧
上から順にプライオリティが高い。

| ログレベル | 内容 |
| :-- | :-- |
| emerg | システムが使用不能なレベル |
| alert | すぐになんとかしないといけない状態 |
| crit | クリティカルなレベル |
| err | エラー |
| warning | ワーニング |
| notice | ちょっと注意したほうがいいレベル |
| info | 情報 |
| debug | デバッグレベル |

引用元: http://www.usupi.org/sysad/207.html


ログディレクトリを作成する。

```
$ sudo mkdir /var/log/python-sample
```

設定を反映

```shell-session
$ sudo systemctl restart rsyslog
```

## ログを出力してみる
### logging設定ファイルを作成する

```ini:logging.cfg
[loggers]
keys = root

[logger_root]
level = INFO
handlers = root

[formatters]
keys = standardFormatter

[formatter_standardFormatter]
format = %(asctime)s.%(msecs)03d %(name)-12s %(levelname)-8s %(message)s
datefmt = %y-%m-%d %H:%M:%S

[handlers]
keys = root

[handler_root]
level = INFO
; syslogに渡すためのhandler指定
class = handlers.SysLogHandler
formatter = standardFormatter
args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_LOCAL7)
```

### ログを出力するPythonコードを作成

```py:sample.py
#!/usr/bin/env /python
# -*- coding:utf-8 -*-
import logging.config

# 先程作成したlogging.cfgを読み込む
logging.config.fileConfig('logging.cfg')
logger = logging.getLogger('__name__')

logger.debug('Debug message')
logger.info('Info message')
logger.warning('Warning message')
logger.error('Error message')
logger.critical('Critical message')
```

## ログを確認

pythonを実行する

```shell-session
$ python sample.py
```

ログを確認

```
$ ls -1 /var/log/python-sample/
production-all.log
production-err.log
production-notice-err.log
production-notice.log
```

```shell-session
$ sudo tailf /var/log/python-sample/production-all.log
```

```
Mar 29 18:58:39 19-03-29 18: 58:39.641 __name__     INFO     Info message
Mar 29 18:58:39 19-03-29 18: 58:39.641 __name__     WARNING  Warning message
Mar 29 18:58:39 19-03-29 18: 58:39.641 __name__     ERROR    Error message
Mar 29 18:58:39 19-03-29 18: 58:39.642 __name__     CRITICAL Critical message
```

## ログをローテートする
- [任意のログをlogrotateを使って管理する](https://qiita.com/Esfahan/items/a8058f1eb593170855a1)

## 参考記事
- [Python: mod_wsgi のログを rsyslog と logrotate でローテーションする](https://blog.amedama.jp/entry/2015/09/13/000901)