最后别忘了Application_Start() log4net.Config.XmlConfigurator.Configure();
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);
Log4net的安装
Install-Package log4net
1.先弄个日志记录的类
////// 使用LOG4NET记录日志的功能,在WEB.CONFIG里要配置相应的节点 /// public class LogHelper { //log4net日志专用 public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo"); public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror"); public static void SetConfig() { log4net.Config.XmlConfigurator.Configure(); } public static void SetConfig(FileInfo configFile) { log4net.Config.XmlConfigurator.Configure(configFile); } ////// 普通的文件记录日志 /// /// public static void WriteLog(string info) { if (loginfo.IsInfoEnabled) { loginfo.Info(info); } } ////// 错误日志 /// /// /// public static void WriteLog(string info, Exception se) { if (logerror.IsErrorEnabled) { logerror.Error(info, se); } } }
在 configSections 节点上添加:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
然后配置单独的节点:
3.在GOLBAL文件里调用写日志:
void Application_Start(object sender, EventArgs e) { //在应用程序启动时运行的代码 //初始日志的配置 LogHelper.SetConfig(); } void Application_Error(object sender, EventArgs e) { //在出现未处理的错误时运行的代码 Exception objExp = HttpContext.Current.Server.GetLastError(); string username = ""; string userid = ""; if (Session["ulogin"] != null) { string[] uinfo=Session["ulogin"].ToString().Split('|'); userid = uinfo[0]; username = uinfo[1]; } Aotain114.Public.LogHelper.WriteLog("\r\n用户ID:"+userid+"\r\n用户名:"+username+"\r\n客户机IP:" + Request.UserHostAddress + "\r\n错误地址:" + Request.Url + "\r\n异常信息:" + Server.GetLastError().Message, objExp); }