2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でlog4netを導入する方法

Last updated at Posted at 2023-07-03

はじめに:
C#プロジェクトを作成した際、log出力用にlog4netを導入することが多いので、
記事として残します。

ステップ1: log4netのインストール
まずは、プロジェクトにlog4netをインストールしましょう。

1.1: NuGetパッケージマネージャーを開きます。
1.2: "log4net"を検索し、該当するパッケージを選択して"インストール"ボタンをクリックします。
1.3: インストールが完了すると、log4netがプロジェクトに追加されます。

ステップ2: log4netの設定
次に、log4netを使用するための設定を行います。

2.1: プロジェクトのルートディレクトリに"log4net.config"という名前の設定ファイルを作成します。
2.2: 設定ファイルに、ログの出力先やログのフォーマットなどを設定します。

例:

<log4net>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="DEBUG" />
    <appender-ref ref="ConsoleAppender" />
  </root>
</log4net>

2.3: AssemblyInfo.csファイルを開き、以下の行を追加します。

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

ステップ3: ログの使用
log4netの設定が完了したら、ログの出力が可能になります。

3.1: log4netを使用するクラスに、以下の行を追加します。

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

3.2: ログを出力したい箇所で、以下のようにログを記述します。

log.Debug("デバッグメッセージです。");
log.Info("インフォメーションメッセージです。");
log.Warn("ワーニングメッセージです。");
log.Error("エラーメッセージです。");
log.Fatal("致命的なメッセージです。");

以上、C#プロジェクトでのlog4netの導入が完了です。ログの設定や使用方法をカスタマイズすることも可能です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?