首页 > 其他分享 >.NET教程 - 日志 & 诊断 (Logs & diagnostics)

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

时间:2022-10-02 09:11:27浏览次数:40  
标签:Logs Trace class WriteLine diagnostics Debug using 日志 NET

更新记录
转载请注明出处:
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)

标签:Logs,Trace,class,WriteLine,diagnostics,Debug,using,日志,NET
From: https://www.cnblogs.com/cqpanda/p/16745037.html

相关文章

  • Kubernetes--Service资源的基础应用
    Service资源的基础应用首先Service资源本身并提供任何服务,其真正处理并响应客户端请求的是后端的Pod资源,这些Pod资源通常由各类控制器对象(ReplicaSet、Deployment、Daemo......
  • repomd.xml signature could not be verified for kubernetes
    repo文件是CentOS中yum源(软件仓库)的配置文件,通常一个repo文件定义了一个或者多个软件仓库的细节内容,例如我们将从哪里下载需要安装或者升级的软件包,repo文件中的设置内容将......
  • INetSim模拟C2 这玩意比起nc来说更专业!
    INetSimINetSim是一个非常方便和强大的实用程序,允许你在一台机器上模拟一堆标准的Internet服务。默认情况下,它将模拟可以轻松调整的DNS,HTTP和SMTP。由于我们后续会将受害......
  • 学习ASP.NET Core Blazor编程系列四——迁移
    学习ASP.NETCoreBlazor编程系列一——综述学习ASP.NETCoreBlazor编程系列二——第一个Blazor应用程序(上)学习ASP.NETCoreBlazor编程系列二——第一个Blazor应......
  • Netty 学习(六):创建 NioEventLoopGroup 的核心源码说明
    Netty学习(六):创建NioEventLoopGroup的核心源码说明作者:Grey原文地址:博客园:Netty学习(六):创建NioEventLoopGroup的核心源码说明CSDN:Netty学习(六):创建NioEventLoopG......
  • VB,NET RichTextBox 计算光标所在行和列的方法
    PrivateSubRichTextBox1_Click(senderAsObject,eAsEventArgs)HandlesRichTextBox1.Click '计算光标所在的位置DimintSelstartAsInteger......
  • .NET Core泛型约束
    .NETCore泛型约束如果一个类/引入了泛型类型,那么可以对引入的泛型写一个约束,让传入的泛型类型必须具备某些条件才能传入publicclassPerson<T>whereT:base-cla......
  • .NET教程 - 加密 & 解密(Encryption & Decryption)
    更新记录转载请注明出处:2022年10月1日发布。2022年9月29日从笔记迁移到博客。常用加密算法Encryptionanddecryption(加密和解密)说明使用Key进行加密和解密Key......
  • Linux华为云Huawei Cloud EulerOS 系统 配置.Net6运行环境
    1.创建华为云HuaweiCloudEulerOS 2.0标准版64位.设置服务器登录密码,最后确认,然后稍等几分钟就可以看到申请的服务器处于运行状态就可以了.   2.远程登录服务......
  • Networkx的入门使用
    创建一个图创建一个没有边edge和节点node的空图:importnetworkxasnxG=nx.Graph()定义:图形是节点和已识别的节点对的集合,即顶点和边(链接)的集合。在networkx中,节点......