刚完成的这个项目需要记录用户操作日志,后来领导就让我在用户操作点上都用log4记录下。
首先把dll,config引入到项目中,然后在AssemblyInfo配置用到的config
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
然后就写一些操作log的类,这个类大牛也给提供了
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PRankBLL { public class LogHelper { public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo"); public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror"); public static void WriteLog(string info) { if (loginfo.IsInfoEnabled) { loginfo.Info(info); } } /// <summary> /// 错误记录 /// </summary> /// <param name="info">附加信息</param> /// <param name="ex">错误</param> public static void ErrorLog(string info, Exception ex) { if (!string.IsNullOrEmpty(info) && ex == null) { logerror.ErrorFormat("【附加信息】 : {0}<br>", new object[] { info }); } else if (!string.IsNullOrEmpty(info) && ex != null) { string errorMsg = BeautyErrorMsg(ex); logerror.ErrorFormat("【附加信息】 : {0}<br>{1}", new object[] { info, errorMsg }); } else if (string.IsNullOrEmpty(info) && ex != null) { string errorMsg = BeautyErrorMsg(ex); logerror.Error(errorMsg); } } /// <summary> /// 美化错误信息 /// </summary> /// <param name="ex">异常</param> /// <returns>错误信息</returns> private static string BeautyErrorMsg(Exception ex) { string errorMsg = string.Format("【异常类型】:{0} <br>【异常信息】:{1} <br>【堆栈调用】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace }); errorMsg = errorMsg.Replace(" ", "<br>"); errorMsg = errorMsg.Replace("位置", "<strong style="color:red">位置</strong>"); return errorMsg; } } }
当然,要在全局环境下记录错误等操作信息的话,你还需要一个Global.asax
protected void Application_Error(object sender, EventArgs e) { // 在出现未处理的错误时运行的代码 Exception objExp = HttpContext.Current.Server.GetLastError(); LogHelper.ErrorLog("<br/><strong>客户机IP</strong>:" + Request.UserHostAddress + "<br /><strong>错误地址</strong>:" + Request.Url, objExp); }//GetIP()
加了这个,按理说应该是会按照你想的那样记录你的普通日志和错误日志了,但是你会发现没效果,因为 loginfo.IsInfoEnabled=false 如果一直为false的话,就不会进入loghelp的write方法,所以要在Global.asax中的Application_Start方法中加入以下代码:
protected void Application_Start(object sender, EventArgs e) { log4net.Config.XmlConfigurator.Configure(); }
然后在程序中应用就是
LogHelper.WriteLog(""+userid+"进入了我的主页页面并且把关注的人绑定到了页面上");
一个log4net就会帮你记录日志了。