第一步:
新建一个公共类库common,添加CustomLog4jLogger.cs 并引用log4net.dll
/// <summary> /// 日志记录 /// </summary> public class CustomLog4jLogger { /// <summary> /// 日志 /// </summary> public static ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// 日志 /// </summary> /// <param name="funcstr">方法名称</param> /// <param name="message">日志描述</param> /// <param name="args">方法参数</param> /// <param name="type">类别,1:错误日志,2:操作日志</param> private static void Log(string apikey, string funcstr, string message, string args, int type) { switch (type) { case 1: Logger.Error(string.Format("Func:{0} | Error:{1} | Args:{2}", funcstr, message, args)); break; case 2: Logger.Info(string.Format("Key:{0} | Func:{1} | Message:{2}", apikey, funcstr, message)); break; case 3: Logger.Warn(message); break; } } /// <summary> /// 错误日志 /// </summary> /// <param name="funcstr">方法名称</param> /// <param name="message">错误信息</param> /// <param name="args">方法参数</param> public static void LogDebug(string funcstr, string message, string args) { Log("", funcstr, message, args, 1); } /// <summary> /// 错误日志 /// </summary> /// <param name="funcstr">方法名称</param> /// <param name="message">错误信息</param> public static void LogDebug(string funcstr, string message) { LogDebug(funcstr, message, ""); } /// <summary> /// 错误日志 /// </summary> /// <param name="message">错误信息</param> public static void LogDebug(string message) { LogDebug("", message); } /// <summary> /// 运行日志 /// </summary> /// <param name="message">运行信息</param> public static void LogInfo(string message) { LogInfo("", message); } /// <summary> /// 运行日志 /// </summary> /// <param name="funcstr">方法名称</param> /// <param name="message">运行信息</param> /// <param name="args">方法参数</param> public static void LogInfo(string funcstr, string message) { LogInfo("", funcstr, message); } /// <summary> /// 运行日志 /// </summary> /// <param name="apikey">应用的apikey</param> /// <param name="funcstr">方法名称</param> /// <param name="message">运行信息</param> /// <param name="args">方法参数</param> public static void LogInfo(string apikey, string funcstr, string message) { Log(apikey, funcstr, message, "", 2); } public static void LogEvent(string message) { Log("", "", message, "", 3); } }
第二步:
在需要记录日志的类库里,引用common类库,调用:
CustomLog4jLogger.LogInfo("xxxxxx");第三步:在调用类库的程序里添加log4net.config(在附件里)并引用log4net.dll程序调用:
static void Main(string[] args) { try { log4net.Config.XmlConfigurator.Configure(new FileInfo(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "log4net.config"))); } }
附件
时间: 2024-11-09 01:59:08