.NET 6:.NETのロギングコンポーネントlog4netを使用する。
この記事では、.NETでのlog4netの使い方を簡単に説明します。
1. まず、空のASP.NET Coreプロジェクトを作成します。
2. Nugetパッケージマネージャで、以下の2つのパッケージをインストールします。
ログ4ネット
Microsoft.Extensions.Logging.Log4Net.AspNetCore(マイクロソフト エクステンション ロギング ロギング アーキテクチャ
画像
3. プロジェクトのルートディレクトリに新しいlog4net設定ファイルlog4net.configを作成し、常にコピーするように設定します。
{{コード{{コード
<?xml version="1.0" encoding="utf-8" ? >
<log4net>
<! --root-configuration-->
<root>
<! -- Logging level: optional values: ERROR > WARN > INFO > DEBUG -->
<level value="ERROR"/>
<level value="WARN"/>
<level value="INFO"/>
<level value="DEBUG"/>
<appender-ref ref="ErrorLog" />
<appender-ref ref="WarnLog" />
<appender-ref ref="InfoLog" />
<appender-ref ref="DebugLog" />
</root>
<! -- error Error.log-->
<appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
<! --directory path, can be relative or absolute -->
<param name="File" value="C:\logs\"/>
<! --filename, generate folder by date -->
<param name="DatePattern" value="/yyyy-MM-dd/"Error.log""/>
<! --append to file-->
<appendToFile value="true"/>
<! -->Method of creating log files, optional values: Date[Date],FileSize[Size],Mixed[Composite]-->
<RollingStyle value="Composite"/>
<! --writing to a file-->
<staticLogFileName value="false"/>
<! -- Single file size. Unit:KB|MB|GB -->
<maximumFileSize value="200MB"/>
<! -- the maximum number of files to keep, set to "-1" then unlimited -->
<maxSizeRollBackups value="-1"/>
<! ---Log format-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%d{HH:mm:ss}]%m%n"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="ERROR" />
</filter>
</appender>
<! -- Warning Warn.log-->
<appender name="WarnLog" type="log4net.Appender.RollingFileAppender">
<! --directory path, can be relative or absolute -->
<param name="File" value="C:\logs\"/>
<! --filename, generate folder by date -->
<param name="DatePattern" value="/yyyy-MM-dd/"Warn.log""/>
<! --append to file-->
<appendToFile value="true"/>
<! -->Method of creating log files, optional values: Date[Date],FileSize[Size],Mixed[Composite]-->
<RollingStyle value="Composite"/>
<! --writing to a file-->
<staticLogFileName value="false"/>
<! -- Single file size. Unit:KB|MB|GB -->
<maximumFileSize value="200MB"/>
<! -- the maximum number of files to keep, set to "-1" then unlimited -->
<maxSizeRollBackups value="-1"/>
<! ---Log format-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%d{HH:mm:ss}]%m%n"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="WARN" />
</filter>
</appender>
<! -- Info Info.log-->
<appender name="InfoLog" type="log4net.Appender.RollingFileAppender">
<! --directory path, can be relative or absolute -->
<param name="File" value="C:\logs\"/>
<! --filename, generate folder by date -->
<param name="DatePattern" value="/yyyy-MM-dd/"Info.log""/>
<! --append to file-->
<appendToFile value="true"/>
<! -->Method of creating log files, optional values: Date[Date],FileSize[Size],Mixed[Composite]-->
<RollingStyle value="Composite"/>
<! --writing to a file-->
<staticLogFileName value="false"/>
<! -- Single file size. Unit:KB|MB|GB -->
<maximumFileSize value="200MB"/>
<! -- the maximum number of files to keep, set to "-1" then unlimited -->
<maxSizeRollBackups value="-1"/>
<! ---Log format-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%d{HH:mm:ss}]%m%n"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</fusing log4net;
var builder = WebApplication.CreateBuilder(args);
//Inject Log4Net
builder.Services.AddLogging(cfg =>
{
cfg.AddLog4Net();
//The default path to the configuration file is in the root directory, and the file name is log4net.config
//If the path or name of the file has changed, you need to reset its path or name
//for example, create a folder named cfg in the project root directory, move the log4net.config file into it, and rename it to log.config
//then you need to use the following code to configure it
//cfg.AddLog4Net(new Log4NetProviderOptions()
//{
// Log4NetConfigFileName = "cfg/log.config",
// Watch = true
//});
});
var app = builder.Build();
// When accessing the root page
app.MapGet("/", (ILogger<Program> logger) =>
{
logger.LogInformation("logger: test it Log4Net="Info");
return "Hello World!";
});
// When accessing the test page
app.MapGet("/test", () =>
{
var log = LogManager.GetLogger(typeof(Program));
log.Info("log: This is a general log message");
});
app.Run();
using log4net;
var builder = WebApplication.CreateBuilder(args);
//Inject Log4Net
builder.Services.AddLogging(cfg =>
{
cfg.AddLog4Net();
//The default path to the configuration file is in the root directory, and the file name is log4net.config
//If the path or name of the file has changed, you need to reset its path or name
//for example, create a folder named cfg in the project root directory, move the log4net.config file into it, and rename it to log.config
//then you need to use the following code to configure it
//cfg.AddLog4Net(new Log4NetProviderOptions()
//{
// Log4NetConfigFileName = "cfg/log.config",
// Watch = true
//});
});
var app = builder.Build();
// When accessing the root page
app.MapGet("/", (ILogger<Program> logger) =>
{
logger.LogInformation("logger: test it Log4Net="Info");
return "Hello World!";
});
// When accessing the test page
app.MapGet("/test", () =>
{
var log = LogManager.GetLogger(typeof(Program));
log.Info("log: This is a general log message");
});
app.Run();
{{コード
{{コード 画像
{{コード
{{コード
5. Run the project and you will see that the log file has been generated
{{コード
6. Extended use: use the simple factory pattern IOC injection into custom classes to use
Create a new
ITestLog4Net
interface file, and define a
Log
method.
and create a new
TestLog4Net
custom class that inherits from the
ITestLog4Net
and implements the
Log
method.
Inject our custom class in Program
TestLog4Net
builder.Services.AddTransient
testLog4Net.Log();
var provider = services.BuildServiceProvider()! ;
var testLog4Net = provider.GetService
testLog4Net.Log();
It is recommended to use the above writeup. After Baidu, the answer is: don't pass the call to BuildServiceProvider() This method should be called only once by the Host. Duplicate service providers may lead to some unexpected errors. If any of you know the exact reason, please tell us, thanks!
Tips: The exclamation mark in the code! indicates that the object will not be empty. Be sure to make sure the object will not be empty before writing it this way, which is a new feature in C#10.
This is the end of this article on using the logging component log4net in .NET 6. I hope it helps you to learn and I hope you will support Scripting House more.
{{コード
ITestLog4Net
{{コード
{{コード
{{コード
Log
{{コード {{itestlog4net, ();
testLog4Net.Log()。 {{/itestlog4net,
{{コード
{{コード
()! ;
{{コード
{{コード
()! ;
testLog4Net.Log()。
{{コード
{{コード
TestLog4Net
{{コード
{{コード
{{コード
関連
-
.netcoreプロジェクトでIStartupFilterを使用するためのチュートリアル
-
pythonでpillowをインストールする3つの方法
-
NETガベージコレクション GC診断ツール dotnet-gcmon 使用方法
-
ASP.NET CoreでURLを設定する5つの方法
-
30分でわかるコング経由の.NETゲートウェイ
-
net core downlink tracking skywalking インストールと使いやすいチュートリアル
-
認証プロセスの記録にjwtを使用したネット
-
再起動を伴わないNET5の設定変更は自動的に反映される
-
asp.net core3.1 cookieとjwtのハイブリッド認証による多様な認証ソリューションの実現
-
非同期タスクキャンセルと監視のネット実装
最新
-
nginxです。[emerg] 0.0.0.0:80 への bind() に失敗しました (98: アドレスは既に使用中です)
-
htmlページでギリシャ文字を使うには
-
ピュアhtml+cssでの要素読み込み効果
-
純粋なhtml + cssで五輪を実現するサンプルコード
-
ナビゲーションバー・ドロップダウンメニューのHTML+CSSサンプルコード
-
タイピング効果を実現するピュアhtml+css
-
htmlの選択ボックスのプレースホルダー作成に関する質問
-
html css3 伸縮しない 画像表示効果
-
トップナビゲーションバーメニュー作成用HTML+CSS
-
html+css 実装 サイバーパンク風ボタン
おすすめ
-
NET6新機能 - 暗黙の名前空間参照
-
.NET Coreでオブジェクトプールを使用する
-
ネットのメモリ管理に関する5つの基本
-
swagger uiをasp.net coreに統合する原理
-
Net Core HttpClient処理 レスポンス圧縮の詳細
-
ASP.NET Core MVC フィルタ
-
ASP.NET Coreで複数のサービス実装クラスをインジェクトする方法
-
ajaxでポップアップアラートボックス
-
CS0234 名前空間 'Microsoft.AspNet' に型または名前空間名 'Mvc' が存在しない (あなたは
-
ASP.NETのオンライン統計とアプリケーションとセッションを使用した訪問履歴