第一步NuGet,在公共类库引用log4net的文件,当然你想在其它类库也可以引用,但建议是在公共类库引用。
第二步在WebApi项目下建立log4net.config 文件,复制以下内容到这个文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- This section contains the log4net configuration settings -->
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logfile/" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<staticLogFileName value="false" />
<datePattern value="yyyyMMdd'.log'" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
第三步在Startup 文件下添加如下代码,标红是我添加的
public class Startup
{
public static ILoggerRepository repository { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
repository = LogManager.CreateRepository("GD.Core");
//指定配置文件
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//log日志注入
services.AddSingleton<ILogger, LogHelper>();
}
第四步在Services层 添加如下代码
namespace Guet.Services
{
/// <summary>
/// 公告表
/// </summary>
public class SysNoticeServices : BaseServices<SysNotice>, ISysNoticeServices
{
private ISysNoticeRepository dal;
private ISysUserRepository SysUserRepository;
private IMapper Mapper;
private readonly IUnitOfWork UnitOfWork;
private ILogger Logger;
public SysNoticeServices(IUnitOfWork UnitOfWork, ISysNoticeRepository dal, IMapper Mapper, ISysUserRepository SysUserRepository, ILogger Logger)
{
this.dal = dal;
base.baseDal = dal;
this.Mapper = Mapper;
this.UnitOfWork = UnitOfWork;
this.SysUserRepository = SysUserRepository;
this.Logger = Logger;
}
第五步,就可以直接通过Logger.Debug();
来源:CSDN
作者:上线就吃代码
链接:https://blog.csdn.net/p445726392/article/details/103918388