1. ホーム
  2. Web プログラミング
  3. ASP.NET
  4. 実用的なヒント

.NET 6:.NETのロギングコンポーネントlog4netを使用する。

2022-01-13 07:56:46

この記事では、.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" /> </f
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();
Usage var testLog4Net = app.Services.GetService()! ; or var services = new ServiceCollection()! ;
var provider = services.BuildServiceProvider()! ;
var testLog4Net = provider.GetService()! ;
testLog4Net.Log();
where a compile warning message will be received using the following style of writing. warning ASP0000: Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. alternatives such as dependency injecting services as parameters to 'Configure'. 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

{{コード

{{コード

{{コード