(精華)2020年7月20日 ASP.NET Core log4.net日誌框架的使用

愚公搬程式碼發表於2020-07-20

首先按照如下兩個包

Install-Package Microsoft.Extensions.Logging.Debug
Install-Package Microsoft.Extensions.Logging.Log4.AspNetCore

在根目錄下新建log4net.Config

<?xml version="1.0" encoding="utf-8"?>
<log4net>
	<!-- Define some output appenders -->
	<appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
		<file value="log\log.txt" />
		<!--追加日誌內容-->
		<appendToFile value="true" />

		<!--防止多執行緒時不能寫Log,官方說執行緒非安全-->
		<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

		<!--可以為:Once|Size|Date|Composite-->
		<!--Composite為Size和Date的組合-->
		<rollingStyle value="Composite" />

		<!--當備份檔案時,為檔名加的字尾-->
		<datePattern value="yyyyMMdd.TXT" />

		<!--日誌最大個數,都是最新的-->
		<!--rollingStyle節點為Size時,只能有value個日誌-->
		<!--rollingStyle節點為Composite時,每天有value個日誌-->
		<maxSizeRollBackups value="20" />

		<!--可用的單位:KB|MB|GB-->
		<maximumFileSize value="3MB" />

		<!--置為true,當前最新日誌檔名永遠為file節中的名字-->
		<staticLogFileName value="true" />

		<!--輸出級別在INFO和ERROR之間的日誌-->
		<filter type="log4net.Filter.LevelRangeFilter">
			<param name="LevelMin" value="ALL" />
			<param name="LevelMax" value="FATAL" />
		</filter>
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
		</layout>
	</appender>
	<root>
		<priority value="ALL"/>
		<level value="ALL"/>
		<appender-ref ref="rollingAppender" />
	</root>
</log4net>

配置方式一:program

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(loggingBuilder =>
{
   loggingBuilder.AddLog4Net();//需要配置檔案
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();//靠Startup來串起來MVC
});

配置方式二:Startup

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            loggerFactory.AddLog4Net();

            app.UseSession();

            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot"))
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

使用方式

public class FirstController : Controller
    {
        private readonly ILogger<FirstController> _logger;
        private readonly ILoggerFactory _loggerFactory;
        public FirstController(ILogger<FirstController> logger,
            ILoggerFactory loggerFactory)
        {
            _logger = logger;
            this._loggerFactory = loggerFactory;
        }

        public IActionResult Index()
        {
            this._logger.LogWarning("日誌1");
            this._loggerFactory.CreateLogger<FirstController>().LogWarning("日誌2");
            return View();
        }
    }

相關文章