日志系统——初识Logging(1)

基本概念

1.日志级别

Trace
记录一些对程序员调试问题有帮助的信息,其中可能包含一些敏感信息, 所以应该避免在生产环境中启用Trace日志
Debug
记录一些在开发和调试阶段有用的短时变量(Short-term usefulness), 所以除非为了临时排除生产环境的故障,开发人员应该尽量避免在生产环境中启用Debug日志
Information
记录应用程序的一些流程, 例如,记录当前api请求的url
Warning
记录应用程序中发生的不正常或者未预期的事件信息。
这些信息中可能包含错误消息或者错误产生的条件, 例如, 文件未找到
Error
记录应用程序中某个操作产生的错误和异常信息。
Critical
记录一些需要立刻修复的问题。例如数据丢失,磁盘空间不足。

2.日志提供者(LoggingProvider)

把日志文件输入到哪里如:控制台、文件、数据库

代码演示

1.首先创建一个.netcore 控制台程序
2.打开nuget包控制台 下载nuget包
Microsoft.Extensions.Logging
Microsoft.Extensions.Logging.Console

1.创建Test类

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace _01_Logging
{
    public class Test
    {
        private ILogger<Test> logger;
        public Test(ILogger<Test> logger)
        {
            this.logger = logger;
        }
        public void Logging()
        {
            logger.LogDebug("开始执行数据库同步");
            logger.LogDebug("connection succed");
            logger.LogWarning("read data faile, retry first");
            //......
            logger.LogWarning("read data faile, retry second");
            logger.LogError("read data faile");
            try
            {
                File.ReadAllText("A:/1.txt");
            }
            catch(Exception ex)
            {
                logger.LogError(ex, "读取文件成功");
            }
        }
    }
}

2.完成Program代码

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

namespace _01_Logging
{
    class Program
    {
        static void Main(string[] args)
        {
            ///模拟startup实例一个ServiceCollection 
            ServiceCollection services = new ServiceCollection();
            services.AddLogging(
                logBuilder=>
                {
                    logBuilder.AddConsole();
                    logBuilder.SetMinimumLevel(LogLevel.Trace);
                }
                );
            //注册服务
            services.AddScoped<Test>();
            //通过服务构建容器,ServiceProvider类型
            using (var sp = services.BuildServiceProvider())
            { ///获取容器中的服务ITestService
                var test1 = sp.GetRequiredService<Test>();
                test1.Logging();
            }
        }
    }
}


posted @   有诗亦有远方  阅读(8)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示