Apache | ログファイル | 特定のログを別ファイルに記録

アクセスログは1つのファイルだけに保存されるわけではない。ログ形式を複数定義し、別々のアクセスログとして複数ファイルに保存することもできる。

デフォルトでhttpd.confファイルに記述されているログフォーマットに、User-Agentだけを別途記録する形式を追加する。

LogFormat "%{User-Agent}i" agent

そして、ログファイル指定で新しいCustomLogを指定する。

CustomLog logs/agent.log agent

実際に適用すると、次のようになる。

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    LogFormat "%{User-Agent}i" agent <--------------------------- ここに追加した。

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access.log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    #CustomLog "logs/access.log" combined
		
    CustomLog logs/agent.log agent <--------------------------- ここに追加した。
		
</IfModule>

これでUser-Agentだけが、別のアクセスログファイルagent.logに記録されるようになる。

httpd.confファイルを編集した後、Apacheを再起動し、Apacheへ適当にアクセスしてログを確認する。

既存のアクセスログを記録していたaccess.logファイルとは別に、新しくagent.logというファイルが作成され、ファイルへアクセスしたブラウザに関する情報だけが記載されていることを確認できる。

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363

上記のログは、Internet Explorer、Edge、Chromeの3つのブラウザで、それぞれApacheで公開されているHTMLファイルを閲覧した場合のものである。