C # Use Log4Net to record logs (advanced)
The content in the configuration file log4net_config.xml is as follows:
- %message%newline />
- %message%newline />
This configuration file can be used to record logs in text files and SQL server databases (which of the following configuration determines when the configuration is enabled ):
Log encapsulation:
////// Log record class (recorded to the database )///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 {}}////// Output log //////Public static void WriteLog (string sInfo) {m_log.Error (sInfo );}////// Record debug information //////Public static void WriteLog (Exception e) {WriteLog (e. toString (); // WriteLog (---------------------------------------- [this exception starts] ------------------------------------); // WriteLog (Message: + e. message); // WriteLog (Source: + e. source); // WriteLog (StackTrace: + e. stackTrace); // WriteLog (TargetSite: + e. targetSite); // WriteLog (---------------------------------------- [this exception Ends] --------------------------------------);} ///// Configure the log4net environment ///Private static void ConfigureLoad () {XmlDocument doc = new XmlDocument (); // use the current dll path string sPath = FilesOperate. GetAssemblyPath (); if (! SPath. endsWith (\) {sPath + =\;} sPath + = LOG4NET_CONFIG; doc. load (@ sPath); XmlElement myElement = doc. documentElement; log4net. config. xmlConfigurator. configure (myElement );}}
////// Log recording class (recorded in a text file )///Public static class LogisTrac {private static readonly string LOG_DIR = log; 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 {}}////// Return the ILog interface ///Private static log4net. ILog Log {get {return m_log ;}}////// Output log //////Public static void WriteLog (string sInfo) {m_log.Error (sInfo );}////// Record debug information //////Public static void WriteLog (Exception e) {WriteLog (-------------------------------------- [this Exception starts] ------------------------------------); WriteLog (Message: + e. message); WriteLog (Source: + e. source); WriteLog (StackTrace: + e. stackTrace); WriteLog (TargetSite: + e. targetSite); WriteLog (-------------------------------------- [end of this exception] --------------------------------------);} ///// Configure the log4net environment ///Private static void ConfigureLoad () {XmlDocument doc = new XmlDocument (); // use the current dll path string sPath = FilesOperate. GetAssemblyPath (); if (! SPath. EndsWith (\) {sPath + =\;}// check whether the Log folder exists. if not, create 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; // modify the path of log.txt to 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 );}}
////// File Operations ///Public static class FilesOperate {////// Obtain the current path of the App \ end //////
Public static string getAppPath () {return GetAssemblyPath ();}////// Obtain the Assembly running path \ end //////
Public static string GetAssemblyPath () {string sCodeBase = System. reflection. assembly. getExecutingAssembly (). codeBase; sCodeBase = sCodeBase. substring (8, sCodeBase. length-8); // 8 is the Length of 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 ;}////// Copy a folder //////Original path ///Target path ///
Public static bool CopyDirectory (string sSourceDirName, string sDestDirName) {if (string. isNullOrEmpty (sSourceDirName) | string. isNullOrEmpty (sDestDirName) {return false;} // do not copy. svn folder 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 replication function 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 }////// Start other applications //////Application name ///Application working directory ///Command line parameters ///Window style 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 ;}}////// Obtain the name of the Local Computer //////
Public static string GetComputerName () {return Dns. GetHostName ();}////// Obtain the computer ip address //////
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 ;}}////// Description: create a directory //////
Public static bool CreateFolder (string sFolder) {// if the Temporary Folder does not exist, create the folder if (! Directory. Exists (sFolder) {Directory. CreateDirectory (sFolder) ;}return true ;}}