1,首先安装log4net
2,创建一个log日志帮助类
using log4net;3.新建一个log4net.config 文件存放在根目录
using log4net.Config;
using log4net.Repository;
using System.IO;
//按你实际情况修改命名空间
namespace project.helpers
{
public class LogHelper
{
private static ILoggerRepository repository { get; set; }
private static ILog _log;
private static ILog log {
get
{
if (_log == null)
{
Configure();
}
return _log;
}
}
public static void Configure(string repositoryName = "NETCoreRepository", string configFile = "log4net.config")
{
repository = LogManager.CreateRepository(repositoryName);
XmlConfigurator.Configure(repository, new FileInfo(configFile));
_log = LogManager.GetLogger(repositoryName, "");
}
public static void Info(string msg)
{
log.Info(msg);
}
public static void Warn(string msg)
{
log.Warn(msg);
}
public static void Error(string msg)
{
log.Error(msg);
}
}
}
<?xml version="1.0" encoding="utf-8" ?>4.调用:
<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="FileAppender" type="log4net.Appender.FileAppender">
<file value="log-file.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</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>
LogHelper.Info("this is Info");5最后在你的本地或服务器上面就能找到这个目录啦(本地需要在bin\Release\netcoreapp3.1目录下面找,服务器直接在根目录找)
LogHelper.Warn("this is Warn");
LogHelper.Error("this is Error");
- 本文标题: netCore中使用log4net记录日志写入本地日志文件
- 文章分类:【.NET/Web】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.