C#: 日志函数

背景:

1.常见的官方日志模块项目过于复杂,且配置过于繁琐,针对这种现象,实现在大型项目中快速定位错误问题;

实现思路:

1.设置当前日志文件路径(获取到当前文件应用程序路径 + \ErrorLog)

2.判断当前日志文件路径是否存在,不存在则创建

3.在当前日志文件路径下创建日志文本

4.判断当前文件是否存在,如果不存在则创建,如果存在则增加

源码:

csharp 复制代码
using System;
using System.IO;

public class Logger
{
    private static StreamWriter streamWriter;

    // 日志级别
    public enum LogLevel
    {
        INFO,
        WARNING,
        ERROR
    }    
    public static void WriteLog(LogLevel level, string message)
    {
        try
        {
            string directoryPath = Environment.CurrentDirectory + "\\ErrorLog";    //在获得文件夹路径(根据你们自己的实际情况去写错误日志文件夹路径)

            // 判断文件夹是否存在,如果不存在则创建
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            string logFilePath = Path.Combine(directoryPath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.log");

            // 判断文件是否存在,如果不存在则创建,如果存在则追加。
            using (streamWriter = !File.Exists(logFilePath) ? File.CreateText(logFilePath) : File.AppendText(logFilePath))
            {
                streamWriter.WriteLine("***********************************************************************");
                streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
                streamWriter.WriteLine($"Log Level: {level}");
                if (message != null)
                {
                    streamWriter.WriteLine($"Message:\r\n{message}");
                }
            }
        }
        finally
        {
            if (streamWriter != null)
            {
                streamWriter.Flush();
                streamWriter.Dispose();
                streamWriter = null;
            }
        }
    }
}

class Program
{
    static void Main()
    {
        // 测试单元
        Logger.WriteLog(Logger.LogLevel.INFO, "This is an informational message.");
        Logger.WriteLog(Logger.LogLevel.WARNING, "This is a warning message.");
        Logger.WriteLog(Logger.LogLevel.ERROR, "This is an error message with some additional information.");
    }
}
相关推荐
Whisper_Sy4 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 网络状态实现
android·java·开发语言·javascript·网络·flutter·php
Bony-4 小时前
Go语言垃圾回收机制详解与图解
开发语言·后端·golang
hmywillstronger4 小时前
【Rhino】【Python】 查询指定字段并cloud标注
开发语言·python
新缸中之脑4 小时前
Weave.js:开源实时白板库
开发语言·javascript·开源
我能坚持多久4 小时前
D16—C语言内功之数据在内存中的存储
c语言·开发语言
leo__5205 小时前
C#与三菱PLC串口通信源码实现(基于MC协议)
开发语言·c#
二十雨辰5 小时前
[python]-函数
开发语言·python
码农水水5 小时前
中国邮政Java面试被问:容器镜像的多阶段构建和优化
java·linux·开发语言·数据库·mysql·面试·php
福楠5 小时前
C++ STL | map、multimap
c语言·开发语言·数据结构·c++·算法
ytttr8735 小时前
地震数据频率波数域变换与去噪的MATLAB实现
开发语言·matlab