log4net 写日志配置
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 写日志配置的更多相关文章
- 验证码在后台的编写,并实现点击验证码图片时时发生更新 C# 项目发布到IIS后不能用log4net写日志
验证码在后台的编写,并实现点击验证码图片时时发生更新 验证码在软件中的地位越来越重要,有效防止这种问题对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试:下面就是实现验证码的基本步骤: ...
- C# 项目发布到IIS后不能用log4net写日志
在代码中正确配置了log4net后,IIS上仍然不能写日志的情况下,只需在写日志的目录添加 IIS_IUSRS 用户,并赋与读写权限即可.
- log4net 写日志
转载地址:https://www.cnblogs.com/vichin/p/6022612.html //基本使用 https://www.cnblogs.com/genesis/p/498562 ...
- 通过代码来调用log4net写日志
1.使用如下配置 http://www.cnblogs.com/chucklu/p/5404813.html 2.调用 string ConfigFile; private void LoadLogC ...
- 怎么在.NetCore3.0 中使用Log4net 写日志 及读取配置文件的信息
1:安装Log4Net的 NuGet 包: 我们通常之需要安装这一个包即可,其他的主包会自动被添加进来: insatll-package Microsoft.Extensions.Logging.L ...
- log4net写日志的时间附带时区信息
<conversionPattern value="%date{yyyy-MM-dd HH:mm:ss.fffzzz} [%thread] %-5level %logger - %me ...
- .Net Core 实践 - 使用log4net记录日志(3)— log4net向ElasticSearch写日志
demo地址:https://github.com/PuzzledAlien/log4net_demo/tree/master/DotNetCoreConsole_V3 Windows 10 安装部署 ...
- log4net独立配置文件配置(winfrom)
log4net配置很多,具体配置步骤不细说,具体说出个人遇到的问题. 在winfrom和web应用程序中配置,在默认配置文件配置都没问题,因为EF也写在默认配置文件中,就会冲突解决办法就是将log4. ...
- Log4Net 的简要配置
引用log4net.dll AssemblyInfo.cs中 [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyF ...
随机推荐
- java之面向对象20160818
本文主要是介绍一下java面向对象编程方面的知识,涉及的内容可能有点多,所以可能会感觉比较笼统,详细请参见<Java编程思想>里面比较具体点. 1.面向对象 和遵循设计原则和设计模式, 目 ...
- move_base的全局路径规划代码研究
algorithmn parameter code 主要是以下三个函数 计算所有的可行点 怎么计算一个点的可行点 从可行点中计算路径path todo algorithmn 算法的解释 Dijkstr ...
- Java修饰符 public、protected、default、private
2.访问修饰符public,private,protected,以及不写(默认)时的区别?答: 修饰符 当前类 同 包 子 类 其他包 public √ √ √ √ protected √ √ √ × ...
- OpenCV---Numpy数组的使用以及创建图片
一:对头像的所有像素进行访问,并UI图像进行像素取反 (一)for循环取反 import cv2 as cv import numpy as np def access_pixels(image): ...
- Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443
环境 阿里云 centos7 node v8.11.3 npm 5.6.0 错误 npm update 解决 ping registry.npmjs.org 发现https://registry.np ...
- 我的Git之旅(1)---git安装、github注册以及一些基本命令
蚂蚁作为一个混码农届的新人来说,看到什么东西都觉得高大上的感觉.最近接触到了git,有种蠢蠢欲动的感觉,想 试一把.因此开启了我的Git之旅.废话不多说,开始我的git之旅. 1.git服务器的选择 ...
- spoj 1825 Free tour II
http://www.spoj.com/problems/FTOUR2/ After the success of 2nd anniversary (take a look at problem FT ...
- 2017ACM暑期多校联合训练 - Team 6 1008 HDU 6103 Kirinriki (模拟 尺取法)
题目链接 Problem Description We define the distance of two strings A and B with same length n is disA,B= ...
- pythonif语句和循环语句
1.if语句用法 # if语句用法(缩进相同的成为一个代码块) score=90 if score>=60: print("合格") print("OK" ...
- Linux下的压缩解压缩
Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通常都是以.tar结尾的.生成tar包后,就可以用其它的程序来进 行压缩了,所以首先就来讲讲t ...