.net8 使用 log4net
新建LogHelper帮助类
using log4net;
namespace WebTestDemo.Helper
{
public class LogHelper()
{
private readonly ILog _logger = LogManager.GetLogger("Common");
public void Info(string msg)
{
_logger.Info(msg);
}
public void Error(string msg)
{
_logger.Error(msg);
}
}
}
在WebTestDemo.Helper (类库)安装引用log4net
使用log4net需要安装引用log4net,若是 ASP.NET Core 项目,则需要安装 Microsoft.Extensions.Logging.Log4Net.AspNetCore。
log4net
在Nuget管理程序中,搜索 "log4net",然后点击安装。
Microsoft.Extensions.Logging.Log4Net.AspNetCore
在Nuget管理程序中,搜索 "Microsoft.Extensions.Logging.Log4Net.AspNetCore",然后点击安装。
在WebTestDemo (网站项目)新建log4net.config
新建文件
设置文件属性为始终复制
配置
<?xml version="1.0" encoding="utf-8" ?>
<!-- log4net.config -->
<log4net>
<!--通用日志类-->
<!--日志类的名字-->
<logger name="Common">
<!--定义记录的日志级别-->
<level value="ALL" />
<!--记录到哪个介质中去-->
<appender-ref ref="RollingLogFileAppender" />
</logger>
<!--其中layout节点的配置说明:
%m(message):输出的日志消息;
%n(newline):换行;
%d(datetime):输出当前语句运行的时刻;
%r(runtime):输出程序从运行到执行到当前语句时消耗的毫秒数;
%t(threadid):当前语句所在的线程ID ;
%p(priority): 日志的当前日志级别;
%c(class):当前日志对象的名称;
%L:输出语句所在的行号;
%F:输出语句所在的文件名;
%-10:表示最小长度为10,如果不够,则用空格填充;-->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--日志路径-->
<param name= "File" value= "Logs/"/>
<!--多线程时采用最小锁定-->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<!--是否是向文件中追加日志-->
<param name= "AppendToFile" value= "true"/>
<!--log保留天数-->
<!--<param name= "MaxSizeRollBackups" value= "10"/>-->
<!--日志文件名是否是固定不变的-->
<param name= "StaticLogFileName" value= "false"/>
<!--日志文件名格式为:2022-05-22.log-->
<param name= "DatePattern" value= "yyyy-MM-dd'.log'"/>
<!--日志根据日期滚动-->
<param name= "RollingStyle" value= "Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%n%d [%t] %-5p %c [%L] - %m %n" />
</layout>
</appender>
<root>
<!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
<level value="all" />
<!--<appender-ref ref="ColoredConsoleAppender"/>-->
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
在程序入口初始化 (Program.cs)
using WebTestDemo.Helper;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;
builder.Logging.AddLog4Net("Configs/log4net.config");
services.AddSingleton<LogHelper>();
services.AddControllersWithViews();
services.AddSession();
var app = builder.Build();
if (app.Environment.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();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
在控制器中调用
using WebTestDemo.Helper;
using WebTestDemo.Models;
using System.Diagnostics;
namespace WebTestDemo.Controllers
{
public class HomeController(LogHelper logHelper) : Controller
{
public IActionResult Index()
{
logHelper.Info($"Access Home/Index {DateTime.Now.ToString()}");
logHelper.Error($"Access Home/Index {DateTime.Now.ToString()}");
return View();
}
}
}
生成并运行程序,在bin下的Logs文件中找到日志文件
2024-01-16 18:08:28,781 [.NET TP Worker] INFO Common [18] - Access Home/Index 2024/1/16 18:08:28
2024-01-16 18:08:28,784 [.NET TP Worker] ERROR Common [23] - Access Home/Index 2024/1/16 18:08:28