log4net写成日期文件的配置,

#配置

1.configuration appSettings
<add key="log4net.Config" value="App_Data\Config\log4net.config" />

2.Global.asax启动调用下,Log4NetRegister()


private static void Log4NetRegister()
{
var log4netFile = System.Web.HttpContext.Current.Server.MapPath("/")+ System.Configuration.ConfigurationManager.AppSettings["log4net.Config"];
if (!System.IO.File.Exists(log4netFile)) return;
log4net.Config.XmlConfigurator.ConfigureAndWatch(
new System.IO.FileInfo(log4netFile)
);
}

 

3.App_Data\Config\log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<log4net>

<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="App_Data\Logs\" />
<param name="AppendToFile" value="true" />
<param name="DatePattern" value="yyyy-MM-dd.LOG" />
<param name="StaticLogFileName" value="false" />
<param name="RollingStyle" value="Date" />
<!--最小锁定模型以允许多个进程可以写入同一个文件-->
<param name="LockingModel" value="log4net.Appender.FileAppender.MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%M] - Line %L:%m%n" />
</layout>
</appender>


<root>
<level value="ALL" />
<!--<appender-ref ref="ADONetAppender" />-->
<appender-ref ref="LogFileAppender" />
</root>
</log4net>

 

 

#效果:

每天日志: App_Data\Logs\yyyy-MM-dd.LOG

内容如:2015-05-07 16:30:52,896 [12] INFO  WebApi.Controllers.UserOrderController [Test1] - Line 394:Test1()

 

 

 

 

 

 

 

 

 

 

#其他,杂-----------




if (string.IsNullOrEmpty(date)) date = DateTime.Now.ToString("yyyy-MM-dd");
var logfile = HttpContext.Current.Server.MapPath("/App_Data/Logs/") + date + ".LOG";
//HttpContextBase
//httpContextBase.ApplicationInstance.Context;
var content = "";
if (!System.IO.File.Exists(logfile)) Erp.HttpResponseStatic.GetOriginalMessage("不存在");
try
{
var fs = new System.IO.FileStream(logfile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);

var sr = new System.IO.StreamReader(fs, System.Text.Encoding.Default);

//StringBuilder sb = new StringBuilder();
var lines = new List<string>();
while (!sr.EndOfStream)
{
lines.Insert(0, sr.ReadLine() + "\r\n");
if (lines.Count > 100) lines.RemoveAt(lines.Count - 1);
}

return Erp.HttpResponseStatic.GetOriginalMessage(string.Concat(lines));
}
catch (Exception ex)
{
return Erp.HttpResponseStatic.GetOriginalMessage(ex.Message);
}

posted @ 2019-05-08 09:13  以函  阅读(139)  评论(0编辑  收藏  举报