【C#】いつもLog4netの設定を忘れる
残念なことに、いつもLog4netの設定を忘れてしまうため、ここにメモを残します。
「日付毎にログファイルを入れ替える」という使い方が多いため、RollingFileAppenderのサンプルを掲載します。
また、設定ファイルはApp.configではなく、専用の設定ファイルを作成しています。
(log4netはNugetで取得してください。)
①Log4netの設定
log4net.config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<configuration> | |
<log4net> | |
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> | |
<!-- ログ・ファイル名の先頭部分 --> | |
<param name="File" value="..\Logs\ApplicationLog" /> | |
<!-- 追加書き込み --> | |
<param name="AppendToFile" value="true" /> | |
<!-- 日付ごとにファイルを作成することを指定 --> | |
<param name="RollingStyle" value="date" /> | |
<!--ファイル名が固定ではないので“false”を指定 --> | |
<param name="StaticLogFileName" value="false" /> | |
<!-- ファイル名の日付部分 --> | |
<param name="DatePattern" value='"_"yyyyMMdd".log"' /> | |
<layout type="log4net.Layout.PatternLayout"> | |
<!-- ログの書式 --> | |
<conversionPattern value="%date{HH:mm:ss.fff}, [%thread], %-5level, (method name) %method, %message%newline" /> | |
</layout> | |
</appender> | |
<root> | |
<!-- レベルの種類 | |
Fatal : 致命的エラー | |
Error : システム停止を伴わないエラー | |
Warn : 警告 | |
Info : 操作ログ | |
Debug : 開発用デバッグ情報 | |
All : すべて | |
--> | |
<level value="All" /> | |
<!-- どのログ出力先を使用するか --> | |
<appender-ref ref="RollingLogFileAppender" /> | |
</root> | |
</log4net> | |
</configuration> |
- 各設定はXML内のコメントのとおりです。
- ログの出力内容は「15:56:29.555, [1], INFO , (method name) Form1_Load, Load Main form.」みたいな感じです。
- メソッド名は、非同期メソッドの場合は「MoveNext」が出力されます。ちゃんと表示させたい方はググってみてください。
②AssemblyInfoにLog4netコンフィグレーションの設定を追加
※AssemblyInfo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Log4net configuration初期化 | |
[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = "log4net.config")] |
③Log4netのロガーインスタンスを取得
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Log4net ロガーインスタンス取得 | |
/// </summary> | |
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); |
- ログを出力したい各クラスに、インスタンス取得を書きます。
④ログを出力します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
using log4net; | |
namespace SampleLog4net | |
{ | |
public partial class Form1 : Form | |
{ | |
/// <summary> | |
/// Log4net ロガーインスタンス取得 | |
/// </summary> | |
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
/// <summary> | |
/// コンストラクタ。 | |
/// </summary> | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
/// <summary> | |
/// フォーム読み込み時にInfoレベルでログを書き出します。 | |
/// </summary> | |
/// <param name="sender">イベント発行元オブジェクト</param> | |
/// <param name="e">イベントデータ</param> | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
Logger.Info("Load Main form."); | |
} | |
/// <summary> | |
/// ボタンポチっとなで、Taskを動かしつつログを出力します。 | |
/// </summary> | |
/// <param name="sender">イベント発行元オブジェクト</param> | |
/// <param name="e">イベントデータ</param> | |
private async void Button1_ClickAsync(object sender, EventArgs e) | |
{ | |
Logger.Info("Start async methods."); | |
var commandTask1 = Task.Run(() => Command1Async()); | |
var commandTask2 = Task.Run(() => Command2Async()); | |
var result = await Task.WhenAll(commandTask1, commandTask2); | |
Logger.Info("End async methods."); | |
MessageBox.Show("処理が終了しました。"); | |
} | |
/// <summary> | |
/// 非同期のタスクメソッド(その1) | |
/// 5秒待ちます。(その前後にログを出力します。) | |
/// </summary> | |
/// <returns>trueを返します。</returns> | |
private async Task<bool> Command1Async() | |
{ | |
Logger.Info("Command1 delay start."); | |
await Task.Delay(5000); | |
Logger.Info("Command1 delay end."); | |
return true; | |
} | |
/// <summary> | |
/// 非同期のタスクメソッド(その2) | |
/// 10秒待ちます。(その前後にログを出力します。) | |
/// </summary> | |
/// <returns>trueを返します。</returns> | |
private async Task<bool> Command2Async() | |
{ | |
Logger.Info("Command2 delay start."); | |
await Task.Delay(10000); | |
Logger.Info("Command2 delay end."); | |
return true; | |
} | |
} | |
} |
- ロガーインスタンス.レベル("メッセージ")で出力できます。
⑤出力されたログ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16:19:04.379, [1], INFO , (method name) Main, Start Main form | |
16:19:06.162, [1], INFO , (method name) Form1_Load, Load Main form. | |
16:19:12.302, [1], INFO , (method name) MoveNext, Start async methods. | |
16:19:12.363, [.NET ThreadPool Worker], INFO , (method name) MoveNext, Command1 delay start. | |
16:19:12.373, [.NET ThreadPool Worker], INFO , (method name) MoveNext, Command2 delay start. | |
16:19:17.402, [.NET ThreadPool Worker], INFO , (method name) MoveNext, Command1 delay end. | |
16:19:22.390, [.NET ThreadPool Worker], INFO , (method name) MoveNext, Command2 delay end. | |
16:19:22.410, [1], INFO , (method name) MoveNext, End async methods. | |
16:19:25.608, [1], INFO , (method name) Main, End Main form |
- ログの出力イメージです。
※Log4netはバージョン2.0.12、VisualStudio2022(preview)、.Net6(preview)で動作確認をしています。
コメント
コメントを投稿