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. 在 Xamarin.Forms 实现密码输入EntryCell

    在 Xamarin.Forms 中,我们通常使用 TableView 来构建输入表单.Xamarin 为我们提供了 EntryCell 用于输入文本,但是其并不支持密码输入,即密码掩码.这里要对 En ...

  2. git使用笔记(十三)ls-files

    By francis_hao    Mar 18,2018   git ls-fles 显示index和工作区的文件的信息. 概要 git ls-files [-z] [-t] [-v]        ...

  3. Spring MVC @PathVariable注解

    下面用代码来演示@PathVariable传参方式 @RequestMapping("/user/{id}") public String test(@PathVariable(& ...

  4. nginx 与 tomcat 组合搭建web服务

    部分内容转自 http://www.cnblogs.com/naaoveGIS/ 1. Web服务 nginx是常用的web服务器,用于获取静态资源,类似的服务器还有apache. tomcat是基于 ...

  5. 2049: [Sdoi2008]Cave 洞穴勘测

    2049: [Sdoi2008]Cave 洞穴勘测 Time Limit: 10 Sec  Memory Limit: 259 MB Submit: 7475  Solved: 3499 [Submi ...

  6. css table-border

    1.table上设边框,td上设边框: <style> table{border-right:1px solid #F00;border-bottom:1px solid #F00} ta ...

  7. linux中操作数据库的使用命令记录

    1,mysql 查看数据库表编码格式: show create table widget; 修改数据库表编码格式: alter table widget default character set u ...

  8. Elasticsearch技术解析与实战(七)Elasticsearch partial update

    普通的partial update 1.插入测试数据 PUT /test_index/test_type/10 { "test_field1": "test1" ...

  9. 【Hadoop】大数据时代,我们为什么使用hadoop

    博客已转移,请借一步说话.http://www.daniubiji.cn/archives/538 我们先来看看大数据时代, 什么叫大数据,“大”,说的并不仅是数据的“多”!不能用数据到了多少TB , ...

  10. 【CodeForces】790 C. Bear and Company 动态规划

    [题目]C. Bear and Company [题意]给定大写字母字符串,交换相邻字符代价为1,求最小代价使得字符串不含"VK"子串.n<=75. [算法]动态规划 [题解 ...