C# 使用Log4Net記錄日誌(進階篇)
配置檔案log4net_config.xml中的內容如下:
<?xml version="1.0" encoding="utf-8" ?>
<!--
.NET application configuration file
This file must have the exact same name as your application with .config appended to it.
For example if your application is ConsoleApp.exe then the config file must be ConsoleApp.exe.config.
It must also be in the same directory as the application.
-->
<!-- This section contains the log4net configuration settings -->
<log4net>
<!-- Define some output appenders -->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="rolling-log.txt" />
<appendToFile value="true" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100" />
<rollingStyle value="Size" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<header value="[Header]
" />
<footer value="[Footer]
" />
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
</layout>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<!-- Example using environment variables in params -->
<!-- <file value="${TMP}\log-file.txt" /> -->
<sppendToFile value="true" />
<!-- An alternate output encoding can be specified -->
<!-- <encoding value="unicodeFFFE" /> -->
<layout type="log4net.Layout.PatternLayout">
<header value="[Header]
" />
<footer value="[Footer]
" />
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline" />
</layout>
<!-- Alternate layout using XML
<layout type="log4net.Layout.XMLLayout" /> -->
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline" />
</layout>
</appender>
<appender name="NetSendAppender" type="log4net.Appender.NetSendAppender">
<threshold value="ERROR" />
<server value="SQUARE" />
<recipient value="nicko" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
</layout>
</appender>
<!-- Example of how to configure the AdoNetAppender to connect to MS Access -->
<appender name="ADONetAppender_Access" type="log4net.Appender.AdoNetAppender">
<connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date" />
</layout>
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="1024" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
</appender>
<!-- Example of how to configure the AdoNetAppender to connect to MS SQL Server -->
<appender name="ADONetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=192.168.110.110;initial catalog=DBtest;integrated security=false;persist security info=True;User ID=sa;Password=saPassword" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<!--
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</layout>
-->
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="ADONetAppender_SqlServer" />
<!--<appender-ref ref="ConsoleAppender" />-->
</root>
</log4net>
該配置檔案可以用於往文字檔案及sql server資料庫中記錄日誌(啟用哪一個由下面的配置決定):<appender-ref ref="LogFileAppender" />
<appender-ref ref="ADONetAppender_SqlServer" />
日誌類封裝:
/// <summary>
/// 日誌記錄類(記錄到資料庫)
/// </summary>
public static class LogisTracToSqlDB
{
private static readonly log4net.ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const string LOG4NET_CONFIG = "log4net_config.xml";
static LogisTracToSqlDB()
{
try
{
ConfigureLoad();
}
catch { }
}
/// <summary>
/// 輸出日誌
/// </summary>
/// <param name="sInfo"></param>
public static void WriteLog(string sInfo)
{
m_log.Error(sInfo);
}
/// <summary>
/// 記錄debug資訊
/// </summary>
/// <param name="e"></param>
public static void WriteLog(Exception e)
{
WriteLog(e.ToString());
//WriteLog("--------------------------------------[本次異常開始]--------------------------------------");
//WriteLog("Message : " + e.Message);
//WriteLog("Source : " + e.Source);
//WriteLog("StackTrace : " + e.StackTrace);
//WriteLog("TargetSite : " + e.TargetSite);
//WriteLog("--------------------------------------[本次異常結束]--------------------------------------\r\n");
}
/// <summary>
/// 配置log4net環境
/// </summary>
private static void ConfigureLoad()
{
XmlDocument doc = new XmlDocument();
//使用當前dll路徑
string sPath = FilesOperate.GetAssemblyPath();
if (!sPath.EndsWith("\\"))
{
sPath += "\\";
}
sPath += LOG4NET_CONFIG;
doc.Load(@sPath);
XmlElement myElement = doc.DocumentElement;
log4net.Config.XmlConfigurator.Configure(myElement);
}
}
/// <summary>
/// 日誌記錄類(記錄到文字檔案中)
/// </summary>
public static class LogisTrac
{
private static readonly string LOG_DIR = "日誌";
private static readonly string LOG_FILE = LOG_DIR + "\\log" + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
private const string LOG4NET_CONFIG = "log4net_config.xml";
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(typeof(LogisTrac));
static LogisTrac()
{
try
{
ConfigureLoad();
}
catch { }
}
/// <summary>
/// 返回ILog介面
/// </summary>
private static log4net.ILog Log
{
get
{
return m_log;
}
}
/// <summary>
/// 輸出日誌
/// </summary>
/// <param name="sInfo"></param>
public static void WriteLog(string sInfo)
{
m_log.Error(sInfo);
}
/// <summary>
/// 記錄debug資訊
/// </summary>
/// <param name="e"></param>
public static void WriteLog(Exception e)
{
WriteLog("--------------------------------------[本次異常開始]--------------------------------------");
WriteLog("Message : " + e.Message);
WriteLog("Source : " + e.Source);
WriteLog("StackTrace : " + e.StackTrace);
WriteLog("TargetSite : " + e.TargetSite);
WriteLog("--------------------------------------[本次異常結束]--------------------------------------\r\n");
}
/// <summary>
/// 配置log4net環境
/// </summary>
private static void ConfigureLoad()
{
XmlDocument doc = new XmlDocument();
//使用當前dll路徑
string sPath = FilesOperate.GetAssemblyPath();
if (!sPath.EndsWith("\\"))
{
sPath += "\\";
}
//檢視Log資料夾是否存在,如果不存在,則建立
string sLogDir = sPath + LOG_DIR;
if (!Directory.Exists(sLogDir))
{
Directory.CreateDirectory(sLogDir);
}
string sLogFile = sPath + LOG_FILE;
sPath += LOG4NET_CONFIG;
doc.Load(@sPath);
XmlElement myElement = doc.DocumentElement;
//修改log.txt的路徑
XmlNode pLogFileAppenderNode = myElement.SelectSingleNode("descendant::appender[@name='LogFileAppender']/file");
// Create an attribute collection from the element.
XmlAttributeCollection attrColl = pLogFileAppenderNode.Attributes;
attrColl[0].Value = sLogFile;
log4net.Config.XmlConfigurator.Configure(myElement);
}
}
/// <summary>
/// 檔案 操作
/// </summary>
public static class FilesOperate
{
/// <summary>
/// 獲取App的當前路徑 \\結束
/// </summary>
/// <returns></returns>
public static string getAppPath()
{
return GetAssemblyPath();
}
/// <summary>
/// 獲取Assembly的執行路徑 \\結束
/// </summary>
/// <returns></returns>
public static string GetAssemblyPath()
{
string sCodeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
sCodeBase = sCodeBase.Substring(8, sCodeBase.Length - 8); // 8是 file:// 的長度
string[] arrSection = sCodeBase.Split(new char[] { '/' });
string sDirPath = "";
for (int i = 0; i < arrSection.Length - 1; i++)
{
sDirPath += arrSection[i] + Path.DirectorySeparatorChar;
}
return sDirPath;
}
/// <summary>
/// 資料夾複製
/// </summary>
/// <param name="sSourceDirName">原始路徑</param>
/// <param name="sDestDirName">目標路徑</param>
/// <returns></returns>
public static bool CopyDirectory(string sSourceDirName, string sDestDirName)
{
if (string.IsNullOrEmpty(sSourceDirName) || string.IsNullOrEmpty(sDestDirName))
{
return false;
}
//不復制.svn資料夾
if (sSourceDirName.EndsWith("svn"))
{
return true;
}
if (sSourceDirName.Substring(sSourceDirName.Length - 1) != Path.DirectorySeparatorChar.ToString())
{
sSourceDirName = sSourceDirName + Path.DirectorySeparatorChar;
}
if (sDestDirName.Substring(sDestDirName.Length - 1) != Path.DirectorySeparatorChar.ToString())
{
sDestDirName = sDestDirName + Path.DirectorySeparatorChar;
}
#region 複製函式
if (Directory.Exists(sSourceDirName))
{
if (!Directory.Exists(sDestDirName))
{
Directory.CreateDirectory(sDestDirName);
}
foreach (string item in Directory.GetFiles(sSourceDirName))
{
File.Copy(item, sDestDirName + System.IO.Path.GetFileName(item), true);
}
foreach (string item in Directory.GetDirectories(sSourceDirName))
{
CopyDirectory(item, sDestDirName + item.Substring(item.LastIndexOf(Path.DirectorySeparatorChar) + 1));
}
}
return true;
#endregion
}
/// <summary>
/// 啟動其他的應用程式
/// </summary>
/// <param name="file">應用程式名稱</param>
/// <param name="workdirectory">應用程式工作目錄</param>
/// <param name="args">命令列引數</param>
/// <param name="style">視窗風格</param>
public static bool StartProcess(string file, string workdirectory, string args, ProcessWindowStyle style)
{
try
{
Process pMyProcess = new Process();
ProcessStartInfo pStartInfo = new ProcessStartInfo(file, args);
pStartInfo.WindowStyle = style;
pStartInfo.WorkingDirectory = workdirectory;
pMyProcess.StartInfo = pStartInfo;
pMyProcess.StartInfo.UseShellExecute = false;
pMyProcess.Start();
return true;
}
catch (Exception ex)
{
//LogAPI.debug(ex);
return false;
}
}
/// <summary>
/// 獲得本地計算機名
/// </summary>
/// <returns></returns>
public static string GetComputerName()
{
return Dns.GetHostName();
}
/// <summary>
/// 獲得計算機IP地址
/// </summary>
/// <returns></returns>
public static string GetIPAddress()
{
try
{
string sComputerName;
sComputerName = GetComputerName();
string sIpAddress = "";
IPAddress[] addr = Dns.GetHostAddresses(sComputerName);
//for (int i = 0; i < addr.Length; i++)
//{
// sIpAddress += addr[i].ToString() + " ";
//}
sIpAddress = addr[0].ToString();
return sIpAddress;
}
catch (Exception ep)
{
//LogAPI.debug(ep);
return "127.0.0.1";
}
}
/// <summary>
/// 描述:建立目錄
/// </summary>
/// <returns></returns>
public static bool CreateFolder(string sFolder)
{
//如果臨時資料夾不存在,則建立該資料夾
if (!Directory.Exists(sFolder))
{
Directory.CreateDirectory(sFolder);
}
return true;
}
}
原始碼下載地址:點選開啟連結
相關文章
- log4net日誌記錄
- Windows服務使用log4net記錄日誌Windows
- 開源日誌記錄元件Log4Net的使用元件
- asp.net Web專案中使用Log4Net進行錯誤日誌記錄ASP.NETWeb
- 用Log4Net來記錄系統的日誌資訊
- 《MySQL 進階篇》十九:事務日誌MySql
- .Net Core(.NET6)中接入Log4net和NLog進行日誌記錄
- Gin 框架 - 使用 logrus 進行日誌記錄框架
- 使用Log4j進行日誌記錄
- .Net Core中使用DiagnosticSource進行日誌記錄
- 記錄騰訊雲使用日誌
- php日誌,記錄日誌PHP
- 使用Redis記錄系統日誌Redis
- 使用Rsyslog記錄Apache日誌Apache
- 使用 .NET Core 的日誌記錄
- 日誌記錄器
- .NET Core使用Nlog記錄日誌
- 使用 logzero 在 Python 中進行簡單日誌記錄Python
- C#原生郵件傳送+傳送日誌記錄C#
- Swoft AOP 記錄使用者操作日誌
- Laravel sql 日誌記錄LaravelSQL
- secureCRT記錄操作日誌Securecrt
- 記錄日誌檔案
- PHP日誌記錄方法PHP
- oracle日誌操作記錄Oracle
- 一個簡單的 C# 非同步日誌記錄器C#非同步
- 日誌記錄 PHP下往linux目錄下寫日誌PHPLinux
- golang常用庫:日誌記錄庫-logrus使用Golang
- Oracle補充日誌及日誌記錄規則Oracle
- db2不記錄日誌插入記錄DB2
- 記錄 | 實習日誌 9
- mysql開啟日誌記錄MySql
- 記錄 sql 查詢日誌SQL
- SecureCRT自動記錄日誌Securecrt
- Appfuse:記錄操作日誌APP
- storm 問題日誌記錄ORM
- 第11章 日誌記錄
- JavaScript進階教程日記JavaScript