重庆熊猫 Loading

.NET教程 - 日志 & 诊断 (Logs & diagnostics)

更新记录
转载请注明出处:
2022年10月2日 发布。
2022年10月1日 从笔记迁移到博客。

日志(logging)

日志的作用

在应用程序中添加代码以记录正在发生,尤其是发生异常时

以便查看日志并使用它们跟踪问题并解决问题

常用日志技术

Debug用于添加在开发过程中写入日志记录

Trace用于添加在开发和发布中都写入的日志记录

实例

日志信息输出到控制台

默认情况下日志信息都会写到控制台

using System;
using System.Diagnostics;

namespace Test
{
    class Panda
    {
        static void Main()
        {
            //调试模式下,会输出显示
            Debug.WriteLine("Panda Debug Test");
            Debug.WriteLine("Panda Debug Test", "SomeTitle");

            Console.WriteLine("Panda Test");

            //调试模式下|发布模式下,都会输出显示
            Trace.WriteLine("Panda Trace Test");

            Console.ReadKey();
        }
    }
}

日志信息写入到文件中

using System;
using System.Diagnostics;
using System.IO;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            //设置日志文件写入到日志文件中
            Trace.Listeners.Add(new TextWriterTraceListener(File.CreateText("log.txt")));
            //自动刷新缓存到日志文件中
            Trace.AutoFlush = true;

            //测试写入日志文件
            Trace.WriteLine($"{DateTime.Now} - {"Warning"} - {"Code"} - {"Some Message"}");
            Trace.Flush();
            Trace.WriteLine($"{DateTime.Now} - {"Error"} -  {"Code"} - {"Some Message"}");
            Trace.Flush();

            //wait
            Console.ReadKey();
        }
    }
}

Diagnostics

说明

诊断和调试工具目前已经跨平台

Windows特有的工具在nuget包中

Microsoft.Windows.Compatibility

命名空间

using System.Diagnostics;

Conditional Compilation(条件编译)

conditionally compile any section of code in C# with preprocessor directives

The preprocessor directives for conditional compilation are #if, #else, #endif, and #elif

You can define a symbol in source code by using the #define directive (in which case the symbol applies to just that file), or in the .csproj file by using a element (in which case the symbol applies to whole assembly)

You can define symbols that apply to every file in an assembly by editing the .csproj file (or in Visual Studio, by going to the Build tab in the Project Properties window). The following defines two constants, TESTMODE and PLAYMODE:

<PropertyGroup>
<DefineConstants>TESTMODE;PLAYMODE</DefineConstants>
</PropertyGroup>

The Conditional Attribute(条件特性)

命名空间

using System.Diagnostics;

实例

[Conditional ("LOGGINGMODE")]
static void LogStatus (string msg)
{
 ...
}

Debug and Trace Classes(调试和追踪类)

说明

Debug and Trace are static classes that provide basic logging and assertion capabilities

区别

The Debug class is intended for debug builds; the Trace class is intended for both debug and release builds

本质

All methods of the Debug class are defined with [Conditional("DEBUG")]
All methods of the Trace class are defined with [Conditional("TRACE")]

基本使用

Both the Debug and Trace classes provide Write, WriteLine, and WriteIf methods
The Trace class also provides the methods TraceInformation, TraceWarning, and TraceError

实例

Debug.Write("Data");
Debug.WriteLine (23 * 34);
int x = 5, y = 3;
Debug.WriteIf(x > y, "x is greater than y");

The Debug and Trace classes both provide Fail and Assert methods. Fail sends the message to each TraceListener in the Debug or Trace class’s Listeners collection (see the following section)

实例

Debug.Fail("File data.txt does not exist!");

实例

Debug.Assert (File.Exists ("data.txt"), "File does not exist!");

实例:

var result = ...
Debug.Assert (result != null);

TraceListener

The Trace class has a static Listeners property that returns a collection of TraceListener instances
These are responsible for processing the content emitted by the Write, Fail, and Trace methods

By default, the Listeners collection of each includes a single listener (DefaultTraceListener). The default listener has two key features

When connected to a debugger such as Visual Studio, messages are written to the debug output window; otherwise, message content is ignored

When the Fail method is called (or an assertion fails), the application is terminated.

You can change this behavior by (optionally) removing the default listener and then adding one or more of your own. You can write trace listeners from scratch (by subclassing TraceListener) or use one of the predefined types:

TextWriterTraceListener writes to a Stream or TextWriter or appends to a file.

EventLogTraceListener writes to the Windows event log (Windows only).

EventProviderTraceListener writes to the Event Tracing for Windows (ETW) subsystem (cross-platform support)

posted @ 2022-10-02 08:57  重庆熊猫  阅读(130)  评论(0编辑  收藏  举报