Objective
In case of errors, anomalies, crashes, etc. after the project is officially launched,
The first thing we often think about is to look at the logs.
So the log is very important for the maintenance of a system.
Statement
The sample code in this article is designed to work with this framework, and the implementation is free to play.
Through all the log systems
Log system, which is often run through all the code of a program;
Imagine if your log was provided entirely by a third-party component;
Then it means that all of your projects must refer to this DLL;
You may say that you can package 2 times, then you still need all the projects to reference your post-packaged log project,
On the other hand
Some log components need to be instantiated before they can be used, such as log4net, which means you have to have a global static variable, or your own two-time package,
But in fact, Microsoft has provided us with 2 very convenient static classes for log records.
System.Diagnostics.Trace and System.Diagnostics.Debug
The documentation for these 2 classes can be seen on MSDN
System.Diagnostics.Trace System.Diagnostics.Debug |
It is very convenient to use without referencing any DLLs.
The method of calling it is also simple
Using System.Diagnostics;
...
...
Trace.traceerror ("This is an error level log");
Trace.tracewarning ("This is a warning-level log");
Trace.traceinformation ("This is an info-level log");
Trace.WriteLine ("This is a normal log");
Trace.flush ();//Immediate output
...
...
Of course, there are more than 4 ways to see MSDN. Trace,debug is called exactly the same way, except that all the methods of debug are:
Indicates that, in release mode (when no debug constants are defined), the method is not compiled (not executed, but not compiled into the program at all).
This means that the Debug.xxx () method runs only in Debug mode, which can save us a lot of things.
Rewrite the log implementation
The default behavior of the methods in trace and debug is to output the console console, which is the same as Console.Write.
But we can do more by changing his listener TraceListener,
The methods that must be implemented are:
void Write (String message);
void WriteLine (String message);
However, you can also proactively rewrite other methods.
Write a Mytracelistener:
Class Mytracelistener:tracelistener
{
public override void Write (String message)
{
File.appendalltext ("D:\\1.log", message);
}
public override void WriteLine (String message)
{
File.appendalltext ("D:\\1.log", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss ") + message + Environment.NewLine);
}
}
Now initialize the Listener trace.listeners in the program portal.
PS: The common use of trace and debug listeners.
static void Main (string[] args)
{
Trace.Listeners.Clear (); Clear the system listener (the one that is output to the console)
TRACE.LISTENERS.ADD (New Mytracelistener ()); Adding Mytracelistener instances
}
Just a few more ways to test it:
private static void Test ()
{
Try
{
int i = 0;
Console.WriteLine (5/i); Exception occurred except 0
}
catch (Exception ex)
{
Trace.traceerror ("Exception occurred:" + ex.) Message);//Record log
}
}
Since most of the methods are overridable, the final output can be very flexible.
Initializing listeners through configuration files
The configuration file initialization listener is slightly more complicated than the direct write code, but also more convenient, we can quickly, do not recompile the system, can be set to log listener.
The demo is as follows:
Example:
We will separate the Projecttracelistener into a single project, compiled into a DLL.
ProjectTraceListener.cs
1:using System;
2:using System.Collections.Generic;
3:using System.Text;
4:using System.Diagnostics;
5:using System.IO;
6:
7:namespace Projectlog
8: {
9: Public class Projecttracelistener:tracelistener
Ten: {
One: Public string FilePath {get; private set;}
12:
: Public Projecttracelistener (string filePath)
: {
: FilePath = FilePath;
: }
17:
: Public override void Write (String message)
: {
: file.appendalltext (FilePath, message);
: }
: Public override void WriteLine (String message)
: {
: file.appendalltext (FilePath, DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss ") + message + Environment.NewLine);
: }
: Public override void Write (object o, String category)
: {
: String message = String. Empty;
: if (!string. IsNullOrEmpty (category))
: {
: message = category + ":";
: }
: If (O is Exception)//If the Parameter object o is compatible with the Exception class, output the exception message + stack, otherwise output o. ToString ()
: {
: var ex = (Exception) o;
: message + = ex. Message + Environment.NewLine;
PNS: message + = ex. StackTrace;
: }
: else if (null! = O)
Max: {
In: message + = O.tostring ();
: }
43:
: WriteLine (message);
: }
: }
47:}
Test in the console project:
App.
1: <?xml version= "1.0" encoding= "Utf-8"?>
2: <configuration>
3: <system.diagnostics>
4: <trace autoflush= "false" indentsize= "4" >
5: <listeners>
6: <clear/>
7: <!--clear Default listener--
8: <!--add a custom listener initializedata is the initialization parameter--
9: <add name= "Projecttracelistener" type= "Projectlog.projecttracelistener, Projectlog, Version=1.0.0.0, Culture=neutral, Publickeytoken=null "initializedata=" D:\Error.log "/>
Ten: </listeners>
One: </trace>
: <switches>
<!--can set the listening level here, you can set the Error,warning,info or leave it blank--
: <add name= "Projecttracelistener" value= "Error"/>
: </switches>
: </system.diagnostics>
: </configuration>
Program.cs
1:using System;
2:using System.Collections.Generic;
3:using System.Text;
4:using System.Diagnostics;
5:using Projectlog;
6:
7:namespace Projectlogdemo
8: {
9: Class Program
Ten: {
One: static void Main (string[] args)
: {
: //Delete initialization code and set it in config file instead
: //trace.listeners.clear (); Clear the system listener (the one that is output to the console)
: //trace.listeners.add (New Projecttracelistener (@ "D:\Error.log"));//Add Projecttracelistener instance
: Test ();
: }
18:
: private static void Test ()
: {
: Try
: {
At: int i = 0;
: Console.WriteLine (5/i);//0 exception occurred
: }
: catch (Exception ex)
: {
: Trace.Write (ex, "Calculation of employee salary anomalies");
: }
: }
: }
32:}
Test in a Web project:
Web. config
1: <?xml version= "1.0"?>
2: <configuration>
3:
4: <appsettings/>
5: <connectionstrings/>
6: <system.web>
7: <compilation debug= "true" >
8:
9: </compilation>
Ten: <!--
One: can be configured by <authentication> section
12:
13:
:-
Page: <authentication mode= "Windows"/>
: <!--
: If an unhandled error occurs during the execution of the request,
the <customErrors> Festival
: You can configure the appropriate processing steps. Specifically,
This section allows developers to configure HTML error pages to be displayed.
to replace the error stack trace.
At: <customerrors mode= "RemoteOnly" defaultredirect= "genericerrorpage.htm" >
: <error statuscode= "403" redirect= "noaccess.htm"/>
: <error statuscode= "404" redirect= "filenotfound.htm"/>
: </customErrors>
:-
28:
£ º </system.web>
: <system.diagnostics>
To: <trace autoflush= "false" indentsize= "4" >
: <listeners>
: <clear/>
: <!--clear Default listener--
: <!--add a custom listener initializedata is the initialization parameter--
£ º <add name= "Projecttracelistener" type= "Projectlog.projecttracelistener, Projectlog, Version=1.0.0.0, Culture=neutral, Publickeytoken=null "initializedata=" D:\Error.log "/>
Panax Notoginseng: </listeners>
: </trace>
: <switches>
Max: <!--You can set the listening level here, you can setup error,warning,info or leave it blank--
In: <add name= "Projecttracelistener" value= "Error"/>
: </switches>
: </system.diagnostics>
: </configuration>
Default.aspx
1:using System;
2:using System.Collections.Generic;
3:using system.web;
4:using System.Web.UI;
5:using System.Web.UI.WebControls;
6:using System.Diagnostics;
7:using Projectlog;
8:
9:namespace Projectlogdemobyweb
10: {
One: public partial class _default:system.web.ui.page
: {
: protected void Page_Load (object sender, EventArgs e)
: {
: //Delete initialization code and set it in config file instead
: //system.diagnostics.trace.listeners.clear (); Clear the system listener (the one that is output to the console)
: //system.diagnostics.trace.listeners.add (New Projectlog.projecttracelistener (@ "D:\Error.log")); Adding Projecttracelistener instances
: Test ();
: }
20:
: private static void Test ()
22:
: Try
: {
: int i = 0;
: Console.WriteLine (5/i);//0 exception occurred
: }
: catch (Exception ex)
: {
: System.Diagnostics.Trace.Write (ex, "Calculation of employee salary anomalies");
: }
: }
: }
34:}
The type parameter in the configuration file can be obtained as follows:
typeof (Mylog.mytracelistener). AssemblyQualifiedName
Expand
Take log4net as an example of how this framework references other log systems.
public class Projecttracelistener:tracelistener
{
Log4net _log = new Log4net ();
Public Mytracelistener (String filepath)
{
_log = new Log4net ();
_log. FilePath = FilePath;
}
public override void Write (String message)
{
_log. Info (message);
}
public override void WriteLine (String message)
{
_log. Info (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss ") + message + Environment.NewLine);
}
}
From: Bing Lin Light Wu's Blog park
Strong program Log with C # self-brought components