首页 .NET/Web netCore中使用log4net记录日志写入本地日志文件

netCore中使用log4net记录日志写入本地日志文件

作者:胡同里的砖头 围观群众:297 更新于:2023-02-17

1,首先安装log4net
2,创建一个log日志帮助类

using log4net;
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);
}
}
}
3.新建一个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="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>
4.调用:
LogHelper.Info("this is Info");
LogHelper.Warn("this is Warn");
LogHelper.Error("this is Error");
5最后在你的本地或服务器上面就能找到这个目录啦(本地需要在bin\Release\netcoreapp3.1目录下面找,服务器直接在根目录找)

  • 本文标题: netCore中使用log4net记录日志写入本地日志文件
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8