C# 日志

本文介绍了一种使用C#实现的日志管理系统,通过文件流形式记录程序运行时的详细信息。系统首先获取程序的DLL路径,并在此基础上创建日志目录。当需要写入日志时,将消息格式化并追加到指定日期的日志文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.文件流形式

public class LogManager
{
    private static string m_RootPath =string.Empty;
    public static string RootPath
    {
        get
        {
            try
            {
                if (string.IsNullOrEmpty(m_RootPath))
                {
                    //获取程序DLL路径
                    string strDLLPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    strDLLPath = strDLLPath.Substring(0, strDLLPath.LastIndexOf("\\") + 1);
                    m_RootPath = strDLLPath + "Logs\\";
                    if (!Directory.Exists(m_RootPath))
                    {
                        Directory.CreateDirectory(m_RootPath);
                    }
                }
                return m_RootPath;
            }
            catch
            {
                throw new DirectoryNotFoundException("取得程序集路径出错!");
            }
            
        }
    }
    public static void WriteLog(string message)
    {
        try
        {
            string logFile = RootPath + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            string newMsg = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]    " + message + "\r\n";
            using (var fs = new FileStream(logFile, FileMode.Append))
            {
                using (var sw = new StreamWriter(fs))
                {
                    sw.Write(newMsg);
                }
            }
        }
        catch
        {
            throw new FileNotFoundException("操作日志文件出错!");
        }            
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值