- Nuget安装log4net,图里的两个
2.项目根目录下添加log4net.config.添加下面的代码:
XML
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- This section contains the log4net configuration settings -->
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log/" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<staticLogFileName value="false" />
<datePattern value="yyyy-MM-dd'.log'" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
- 添加一个logHelper.cs
cs
public class LogHelper
{
private static readonly ILog logger;
static LogHelper()
{
if (logger == null)
{
var repository = LogManager.CreateRepository("NETCoreRepository");
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
logger = LogManager.GetLogger(repository.Name, "InfoLogger");
}
}
/// <summary>
/// 普通日志
/// </summary>
/// <param name="message"></param>
/// <param name="exception"></param>
public static void Info(string message, Exception exception = null)
{
if (exception == null)
logger.Info(message);
else
logger.Info(message, exception);
}
/// <summary>
/// 告警日志
/// </summary>
/// <param name="message"></param>
/// <param name="exception"></param>
public static void Warn(string message, Exception exception = null)
{
if (exception == null)
logger.Warn(message);
else
logger.Warn(message, exception);
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="message"></param>
/// <param name="exception"></param>
public static void Error(string message, Exception exception = null)
{
if (exception == null)
logger.Error(message);
else
logger.Error(message, exception);
}
}
- 调用:
cs
LogHelper.Info("test Info log"); //普通日志
LogHelper.Warn("test Warn log"); //告警日志
LogHelper.Error("test Error log"); //错误日志
项目里就会生成log文件