6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

複数行にまたがるログを1つのログとして取り込んでみた

Last updated at Posted at 2025-02-13

New RelicのInfrastructureエージェントはログファイルを指定することでログをNew Relicに送ることができますが、特定のログに関しては複数行のログを1つのログとしてまとめて送付することができるようになったので試してみたいと思います。

Infrastructureエージェントを使ったログ送付はこちらを参照ください。

また、複数行のログを一つにすることができる対象は下記を参照ください。

概要

EC2上で複数行のログを出力するPythonプログラムを動かして、InfrastructureエージェントでPythonプログラムが出力したログをNew Relicに送付します。

:one: EC2にInfrastructureエージェントをインストール

まず、EC2(Amazon Linux 2023)を立ち上げて、New RelicのInfrastructureエージェントをインストールします。
詳細は下記を参照ください。

:two: 複数行のログを出力するPythonプログラム

ZeroDivisionErrorを発生させるPythonプログラムを用意して、/home/ec2-user/example/ に配置します。

multilinelog.py
import logging

logging.basicConfig(
    level=logging.DEBUG,
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('example.log') 
    ]
)

def generate_multiline_log():
    try:
        1 / 0
    except ZeroDivisionError as e:
        logging.error("An error occurred:\n%s", e, exc_info=True) 

if __name__ == "__main__":
    generate_multiline_log()

実行すると同じディレクトリのexample.logにログが出力されます。

$ python3 multilinelog.py 
ERROR:root:An error occurred:
division by zero
Traceback (most recent call last):
  File "/home/ec2-user/example/multilinelog.py", line 13, in generate_multiline_log
    1 / 0
ZeroDivisionError: division by zero

:three: Pythonプログラムのログを送付する設定

/etc/newrelic-infra/logging.d の配下に python-log.yml を作成します。

python-log.yml
logs:
  - name: python.log
    file: /home/ec2-user/example/example.log
    attributes:
      logtype: python_logs

この状態でPythonプログラムを実行すると、Tracebackが4つログとして別々にNew Relic上に表示されます。

image.png

:four: 複数行ログを1つのログとして送付する

複数行のログを1つのログとして送付するためには multilineParser: python を追加します。

python-log.yml
logs:
  - name: python.log
    file: /home/ec2-user/example/example.log
    multilineParser: python
    attributes:
      logtype: python_logs

この状態でPythonプログラムを実行すると、Tracebackが1つのログとしてNew Relic上に表示されました!

image.png

image.png

その他

New Relicでは、新しい機能やその活用方法について、QiitaやXで発信しています!
無料でアカウント作成も可能なのでぜひお試しください!

New Relic株式会社のX(旧Twitter)Qiita OrganizationOrganizationでは、
新機能を含む活用方法を公開していますので、ぜひフォローをお願いします。

無料のアカウントで試してみよう!
New Relic フリープランで始めるオブザーバビリティ!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?