1.nuget装log4net
2.nuget控件台装 mysql.data
Install-Package mysql.data -version 6.8.3 (太高的版本用不了,切记)
3.修改app.config文件,在configuration节点下添加
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlConnection, MySql.Data, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Common
{
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("\r\n", "<br>");
errorMsg = errorMsg.Replace("位置", "<strong style=\"color:red\">位置</strong>");
return errorMsg;
} }
}
using Common;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testLog4N
{
public class LogExceptionHandle
{
private static string _ConnectionString = "server=xxx;port=3306;database=xxx;uid=xxx;pwd=xxx;";
/// <summary>
/// 绑定程序中的异常处理
/// </summary>
public static void BindExceptionHandler()
{
//设置应用程序处理异常方式:ThreadException处理
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理未捕获的异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//加载log4net组件
LoadADONetAppender();
}
/// <summary>
/// 处理UI线程异常
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
LogHelper.ErrorLog(null, e.Exception as Exception);
}
/// <summary>
/// 处理未捕获的异常
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
LogHelper.ErrorLog(null, e.ExceptionObject as Exception);
}
/// <summary>
/// 使用SQLSERVER记录异常日志
/// </summary>
/// <Author>Ryanding</Author>
/// <date>2011-05-01</date>
public static void LoadADONetAppender()
{ log4net.Repository.Hierarchy.Hierarchy hier =
log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy; if (hier != null)
{
log4net.Appender.AdoNetAppender adoAppender = new log4net.Appender.AdoNetAppender();
adoAppender.Name = "AdoNetAppender";
adoAppender.CommandType = CommandType.Text;
adoAppender.BufferSize = ;
adoAppender.ConnectionType = "MySql.Data.MySqlClient.MySqlConnection, MySql.Data, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d";
adoAppender.ConnectionString = _ConnectionString;
adoAppender.CommandText = @"INSERT INTO `ddylog` (`Date`, `Thread`, `Level`, `Logger`, `Method`, `Location`,`Message`,`Exception`) VALUES (@Date, @Thread, @Level, @Logger, @Method,@Location,@Message,@Exception)";
adoAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Date",
DbType = System.Data.DbType.DateTime,
Layout = new log4net.Layout.RawTimeStampLayout()
});
adoAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Thread",
DbType = System.Data.DbType.String,
Size = ,
Layout = new Layout2RawLayoutAdapter(
new PatternLayout("%thread")
)
});
adoAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Level",
DbType = System.Data.DbType.String,
Size = ,
Layout = new Layout2RawLayoutAdapter(
new PatternLayout("%level")
)
});
adoAppender.AddParameter(
new AdoNetAppenderParameter
{
ParameterName = "@Logger",
DbType = System.Data.DbType.String,
Size = ,
Layout = new Layout2RawLayoutAdapter(
new PatternLayout("%logger")
)
});
adoAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Method",
DbType = System.Data.DbType.String,
Size = ,
Layout = new Layout2RawLayoutAdapter(new PatternLayout("%method")
)
});
adoAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Location",
DbType = System.Data.DbType.String,
Size = ,
Layout = new Layout2RawLayoutAdapter(
new PatternLayout("%location")
)
});
adoAppender.AddParameter(
new AdoNetAppenderParameter
{
ParameterName = "@Message",
DbType = System.Data.DbType.String,
Size = ,
Layout = new Layout2RawLayoutAdapter(
new PatternLayout("%message")
)
});
adoAppender.AddParameter(
new AdoNetAppenderParameter
{
ParameterName = "@Exception",
DbType = System.Data.DbType.String,
Size = ,
Layout = new Layout2RawLayoutAdapter(new ExceptionLayout()
)
});
adoAppender.ActivateOptions();
BasicConfigurator.Configure(adoAppender);
}
}
/// <summary>
/// 使用文本记录异常日志
/// </summary>
/// <Author>Ryanding</Author>
/// <date>2011-05-01</date>
public static void LoadFileAppender()
{
string currentPath = AppDomain.CurrentDomain.BaseDirectory;
string txtLogPath = string.Empty;
string iisBinPath = AppDomain.CurrentDomain.RelativeSearchPath; if (!string.IsNullOrEmpty(iisBinPath))
txtLogPath = Path.Combine(iisBinPath, "ErrorLog.html");
else
txtLogPath = Path.Combine(currentPath, "ErrorLog.html"); log4net.Repository.Hierarchy.Hierarchy hier =
log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy; FileAppender fileAppender = new FileAppender();
fileAppender.Name = "LogFileAppender";
fileAppender.File = txtLogPath;
fileAppender.AppendToFile = true; PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "<HR COLOR=red>%n【异常时间】:%d [%t] <BR>%n【异常级别】:%-5p <BR>%n【异 常 类】:%c [%x] <BR>%n%m <BR>%n <HR Size=1>";
patternLayout.ActivateOptions();
fileAppender.Layout = patternLayout; //选择UTF8编码,确保中文不乱码。
fileAppender.Encoding = Encoding.UTF8; fileAppender.ActivateOptions();
BasicConfigurator.Configure(fileAppender); }
}
}
使用:
LogExceptionHandle.BindExceptionHandler();//绑定程序中的异常处理