1、

nuget install package log4net

2、站点跟目录新建配置文件 LogWriterConfig.xml

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net-net-2.0"/>
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</root> <logger name="Idc.Logger" additivity="false">
<appender-ref ref="LogFileAppender" />
</logger> <!--Log File Setting-->
<appender name ="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value ="Log\Trace-"/>
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="" />
<param name="MaxFileSize" value="" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value="yyyy.MM.dd'.log'" />
<param name="RollingStyle" value ="Date" /> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss,fff} %-5p : %m%n"/>
</layout> <!--FATAL > ERROR > WARN > INFO > DEBUG-->
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
</log4net>
</configuration>

3、新建类

  public class LogWriter
{
private ILog _log4Net = null;
private const string DEFAULT_LOGGER_NAME = "Logger";
/// <summary>
/// Prevents a default instance of the <see cref="LogWriter"/> class from being created.
/// </summary>
/// <param name="log4NetInstance">The log4net instance to be used.</param>
private LogWriter(ILog log4NetInstance)
{
_log4Net = log4NetInstance;
} /// <summary>
/// Gets a logger with the specified configuration name.
/// </summary>
/// <param name="configName">Name of the logger in the configuration.</param>
/// <returns>The logger obtained.</returns>
/// <exception cref="System.Configuration.ConfigurationException">Thrown when no logger with the specified configuration name was found.</exception>
public static LogWriter GetLogger(string configName)
{
var logger = LogManager.GetLogger(configName);
if (logger == null)
{
throw new ArgumentException(string.Format("No logger configuration named '{0}' was found in the configuration.", configName), "configName");
}
return new LogWriter(logger);
} /// <summary>
/// Gets the default.
/// </summary>
public static LogWriter Default
{
get
{
return GetLogger(DEFAULT_LOGGER_NAME);
}
} /// <summary>
/// Writes an information level logging message.
/// </summary>
/// <param name="message">The message to be written.</param>
public void WriteInfo(object message)
{
_log4Net.Info(message);
} /// <summary>
/// Writes a warning level logging message.
/// </summary>
/// <param name="message">The message to be written.</param>
public void WriteWarning(object message)
{
_log4Net.Warn(message);
} /// <summary>
/// Writes a warning level logging message.
/// </summary>
/// <param name="message">The message to be written.</param>
/// <param name="exception">The exception.</param>
public void WriteWarning(object message, System.Exception exception)
{
_log4Net.Warn(message, exception);
} /// <summary>
/// Writes the error.
/// </summary>
/// <param name="message">The message to be written.</param>
public void WriteError(object message)
{
_log4Net.Error(message);
} /// <summary>
/// Writes the error level logging message..
/// </summary>
/// <param name="message">The message to be written.</param>
/// <param name="exception">The exception.</param>
public void WriteError(object message, System.Exception exception)
{
_log4Net.Error(message, exception);
} /// <summary>
/// Writes the fatal error level logging message..
/// </summary>
/// <param name="message">The message to be written.</param>
public void WriteFatal(object message)
{
_log4Net.Fatal(message);
} /// <summary>
/// Writes the fatal error level logging message..
/// </summary>
/// <param name="message">The message to be written.</param>
/// <param name="exception">The exception.</param>
public void WriteFatal(object message, System.Exception exception)
{
_log4Net.Fatal(message, exception);
} public void DeleteLog()
{
string logDirPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Log");
if (!Directory.Exists(logDirPath)) return;
int days =;
foreach (string filePath in Directory.GetFiles(logDirPath))
{
DateTime dt;
DateTime.TryParse(Path.GetFileNameWithoutExtension(filePath).Replace(@"Log\", "").Replace(".", "-"), out dt);
if (dt.AddDays(days).CompareTo(DateTime.Now) < )
{
File.Delete(filePath);
}
}
}
}

4、在Global.asax 文件cs 里面加入代码

 protected void Application_Start () {
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WeixinConfig.Register();
log4net.Config.XmlConfigurator.Configure(new FileInfo("LogWriterConfig.xml"));
LogWriter.Default.WriteWarning("app started.");
} protected void Application_End () {
LogWriter.Default.WriteWarning("app stopped.");
}
protected void Application_Error (object sender, EventArgs e) {
Exception ex = Server.GetLastError().GetBaseException();
StringBuilder str = new StringBuilder();
str.Append("\r\n.客户信息:");
string ip = "";
if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null) {
ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
} else {
ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
}
str.Append("\r\n\tIp:" + ip);
str.Append("\r\n\t浏览器:" + Request.Browser.Browser.ToString());
str.Append("\r\n\t浏览器版本:" + Request.Browser.MajorVersion.ToString());
str.Append("\r\n\t操作系统:" + Request.Browser.Platform.ToString());
str.Append("\r\n.错误信息:");
str.Append("\r\n\t页面:" + Request.Url.ToString());
str.Append("\r\n\t错误信息:" + ex.Message);
str.Append("\r\n\t错误源:" + ex.Source);
str.Append("\r\n\t异常方法:" + ex.TargetSite);
str.Append("\r\n\t堆栈信息:" + ex.StackTrace);
str.Append("\r\n--------------------------------------------------------------------------------------------------");
//创建路径
LogWriter.Default.WriteError(str.ToString());
}

5、项目 AssemblyInfo.cs 文件加入

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "LogWriterConfig.xml", Watch = true)]

6、大功告成可以在开发使用了

log4net 写日志配置的更多相关文章

  1. 验证码在后台的编写,并实现点击验证码图片时时发生更新 C# 项目发布到IIS后不能用log4net写日志

    验证码在后台的编写,并实现点击验证码图片时时发生更新   验证码在软件中的地位越来越重要,有效防止这种问题对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试:下面就是实现验证码的基本步骤: ...

  2. C# 项目发布到IIS后不能用log4net写日志

    在代码中正确配置了log4net后,IIS上仍然不能写日志的情况下,只需在写日志的目录添加 IIS_IUSRS 用户,并赋与读写权限即可.

  3. log4net 写日志

    转载地址:https://www.cnblogs.com/vichin/p/6022612.html   //基本使用 https://www.cnblogs.com/genesis/p/498562 ...

  4. 通过代码来调用log4net写日志

    1.使用如下配置 http://www.cnblogs.com/chucklu/p/5404813.html 2.调用 string ConfigFile; private void LoadLogC ...

  5. 怎么在.NetCore3.0 中使用Log4net 写日志 及读取配置文件的信息

    1:安装Log4Net的 NuGet 包: 我们通常之需要安装这一个包即可,其他的主包会自动被添加进来: insatll-package  Microsoft.Extensions.Logging.L ...

  6. log4net写日志的时间附带时区信息

    <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss.fffzzz} [%thread] %-5level %logger - %me ...

  7. .Net Core 实践 - 使用log4net记录日志(3)— log4net向ElasticSearch写日志

    demo地址:https://github.com/PuzzledAlien/log4net_demo/tree/master/DotNetCoreConsole_V3 Windows 10 安装部署 ...

  8. log4net独立配置文件配置(winfrom)

    log4net配置很多,具体配置步骤不细说,具体说出个人遇到的问题. 在winfrom和web应用程序中配置,在默认配置文件配置都没问题,因为EF也写在默认配置文件中,就会冲突解决办法就是将log4. ...

  9. Log4Net 的简要配置

    引用log4net.dll AssemblyInfo.cs中 [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyF ...

随机推荐

  1. Python多线程、进程、协程

    本节内容 操作系统发展史介绍 进程.与线程区别 python GIL全局解释器锁 线程 语法 join 线程锁之Lock\Rlock\信号量 将线程变为守护进程 Event事件 queue队列 生产者 ...

  2. 在VS2010中使用Git【图文】

    http://blog.csdn.net/laogong5i0/article/details/10974285 在之前的一片博客<Windows 下使用Git管理Github项目>中简单 ...

  3. VirtualBox安装虚拟机全过程

    使用Virtual Box安装虚拟机,虚拟机操作系统使用CentOS7进行安装,安装完成后解决网络设置的问题. 一.虚拟机新建过程 1.点击新建. 2.设置内存大小,点击下一步. 3.选择虚拟硬盘,点 ...

  4. 学习笔记:使用opencv做双目测距(相机标定+立体匹配+测距).

    最近在做双目测距,觉得有必要记录点东西,所以我的第一篇博客就这么诞生啦~ 双目测距属于立体视觉这一块,我觉得应该有很多人踩过这个坑了,但网上的资料依旧是云里雾里的,要么是理论讲一大堆,最后发现还不知道 ...

  5. PID控制算法的C语言实现三 位置型PID的C语言实现

    上一节中已经抽象出了位置性PID和增量型PID的数学表达式,这一节,重点讲解C语言代码的实现过程,算法的C语言实现过程具有一般性,通过PID算法的C语言实现,可以以此类推,设计其它算法的C语言实现. ...

  6. Codeforces 717.F Heroes of Making Magic III

    F. Heroes of Making Magic III time limit per test 3 seconds memory limit per test 256 megabytes inpu ...

  7. xshell输入奇怪,空格间距变大

    https://www.macx.cn/thread-2018939-1-1.html 按一下shift+空格就行了 全角/半角转换的快捷键... dd

  8. python学习(十一)测试和调试

    最近学习了python的错误处理和几种测试方法 1 try except 可以通过try except方式捕捉异常 try: print('try...') r = 10/0 print('resul ...

  9. ls乱码问题解决

    http://note.youdao.com/noteshare?id=c7ff510525b4dadaabb6f6a0a72040cc

  10. Prefetch count--预取数量

    一.前言 前面提到如果有多个消费者同时订阅同一个Queue中的消息,Queue中的消息会被平摊给多个消费者.这时如果每个消息的处理时间不同,就有可能会导致某些消费者一直在忙,而另外一些消费者很快就处理 ...