Use C #'s built-in component strong program logs,

Source: Internet
Author: User
Tags log4net

Use C #'s built-in component strong program logs,

If errors, exceptions, or crashes occur after the project is officially launched

The first thing we often think of is to view logs.

Therefore, logs are very important for the maintenance of a system.

Statement

The code in the text is just a chestnut, a very simple Chestnut, but it just shows how the framework works.

The specific implementation can be freely used ~~~~

All log systems

Log systems often run through all the code of a program;

Imagine if your logs are completely provided by third-party components;

This means that all your projects must reference this dll;

Maybe you can encapsulate it twice, so you still need to reference your encapsulated log project for all projects.

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 you have to encapsulate it twice.

 

However, Microsoft has provided us with two very convenient static classes for logging.

System. Diagnostics. Trace and System. Diagnostics. Debug

For more information about the two classes, see MSDN.

System.Diagnostics.Trace

System.Diagnostics.Debug

His use is so convenient that you will fall in love with him once you use it.

You don't need to reference any dll, because it is Microsoft's own thing, it is in System. dll.

It's easy to call his method.
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 common log"); Trace. flush (); // output immediately ......

Of course, there are more than four methods. For more information, see MSDN.

Trace and Debug call methods are identical. The difference lies in

All Debug methods have

[Conditional("DEBUG")]

It indicates that in the Release mode (when the DEBUG constant is not defined), this method will not be compiled (not executed, but will not be compiled into the program at all)

That is to say, the Debug. XXX () method only runs in Debug mode, which saves us a lot of trouble.

Log rewriting implementation

By default, Trace and Debug methods are output to the Console, which is the same as Console. Write.

However, we can change the {sensitive word} TraceListener to perform more operations.

Required methods include:

void Write(string message);void WriteLine(string message);

However, you can also manually override 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 {sensitive word} Trace. Listeners is initialized in the program entry.

PS: Shared Trace and Debug {sensitive word}

Static void Main (string [] args) {Trace. listeners. clear (); // Clear the system {sensitive word} (that is, the one output to the Console) Trace. listeners. add (new MyTraceListener (); // Add a MyTraceListener instance}

In a method test

Private static void Test () {try {int I = 0; Console. writeLine (5/I); // Exception except 0} catch (Exception ex) {Trace. traceError ("exception:" + ex. message); // logs }}

Most of the methods can be rewritten, so the final output can be flexibly processed.

For example

Public override void Write (object o, string category) {string msg = ""; if (string. isNullOrWhiteSpace (category) = false) // The category parameter is not empty. {msg = category + ":" ;}if (o is Exception) // if the parameter o is an Exception class, output exception message + stack; otherwise, output o. toString () {var ex = (Exception) o; msg + = ex. message + Environment. newLine; msg + = ex. stackTrace;} else if (o! = Null) {msg = o. ToString ();} WriteLine (msg );}
Private static void Test () {try {int I = 0; Console. writeLine (5/I); // Exception except 0} catch (Exception ex) {Trace. write (ex, "employee salary calculation exception ");}}

The others are just like nothing else.

Initialize {sensitive words} through the configuration file}

Initializing {sensitive words} through the configuration file is a little more complex than writing code directly, but it is also more convenient. We can quickly, without re-compiling the system, you can set the log {sensitive word }.

Especially in Web projects, this will become more convenient

 

I have just compiled MyTraceListener into a project as a dll.

Add a constructor and the FilePath attribute to set the location of the log file.

MyTraceListener configuration file
xml version="1.0" encoding="utf-8" ?><configuration>  <system.diagnostics>    <trace autoflush="false" indentsize="4">      <listeners>        <clear />                <add name="MyTraceListener" type="MyLog.MyTraceListener, MyLog, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" initializeData="d:\1.log" />      listeners>    trace>    <switches>            <add name="MyTraceListener" value="Error" />    switches>  system.diagnostics>configuration>

The type parameter can be obtained in this way.

typeof(MyLog.MyTraceListener).AssemblyQualifiedName

Version, Culture, and PublicKeyToken can also be ignored.

Test

No problem

If you use third-party components such as log4net, you only need to reference log4net in the project that implements TraceListener.

public class MyTraceListener : 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);    }}

In this way, can I use log4net? Can I use other log systems? If I want to write a database, I want to write a file if I want to write a file, what should I do when I write ~~~~~~

Bro ~~~~~~~

Finished... bye-bye ~~

This article reprinted to: http://www.lupaworld.com/article-237418-1.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.