C#(Log)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace pre_commit
{

       //string strYMD = "log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
    public class Log
    {
        private string logFile;
        private StreamWriter writer;
        private FileStream fileStream = null;

        public Log(string fileName)
        {
            logFile = fileName;
            CreateDirectory(logFile);
        }
        //使用
        //Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
        //log.log(basePath);
        public void log(string info)
        {
            try
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile);
                if (!fileInfo.Exists)
                {
                    fileStream = fileInfo.Create();
                    writer = new StreamWriter(fileStream);
                }
                else
                {
                    fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
                    writer = new StreamWriter(fileStream);
                }
                writer.WriteLine(DateTime.Now + ": " + info);
                writer.WriteLine("----------------------------------");
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
        }

        public void CreateDirectory(string infoPath)
        {
            DirectoryInfo directoryInfo = Directory.GetParent(infoPath);
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }
        }
    }
}
 

### C# 日志记录方法和库 在 C# 编程语言中,日志记录是应用程序开发中的重要部分,用于调试、监控和分析应用程序的行为。以下是几种常见的日志记录方法和库: #### 1. 使用内置的 `System.Diagnostics` 命名空间 C# 提供了内置的日志记录功能,通过 `System.Diagnostics` 命名空间可以使用 `Trace` 和 `Debug` 类进行日志记录。这些类允许开发者将信息输出到跟踪侦听器(Trace Listener),例如控制台或文件[^4]。 ```csharp using System.Diagnostics; Trace.WriteLine("This is a trace message."); Debug.WriteLine("This is a debug message."); ``` #### 2. 使用 NLog 库 NLog 是一个流行的开源日志记录库,支持多种目标(如文件、数据库、网络等)和灵活的配置选项。它可以通过 NuGet 包管理器安装,并提供强大的日志记录功能[^4]。 ```csharp using NLog; class Program { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { logger.Info("Application started."); logger.Debug("This is a debug message."); logger.Warn("This is a warning message."); logger.Error("An error occurred."); } } ``` #### 3. 使用 Serilog 库 Serilog 是另一个广泛使用的日志记录库,以其简洁的 API 和丰富的扩展性著称。它可以轻松地与各种存储后端集成,例如文件、数据库和消息队列[^4]。 ```csharp using Serilog; class Program { static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .WriteTo.File("log.txt") .CreateLogger(); Log.Information("Application started."); Log.Warning("This is a warning message."); Log.Error("An error occurred."); Log.CloseAndFlush(); } } ``` #### 4. 使用 Microsoft.Extensions.Logging Microsoft 提供了一个抽象的日志记录框架 `Microsoft.Extensions.Logging`,它允许开发者通过依赖注入的方式集成不同的日志记录提供程序(如 Console、Debug、EventLog 等)。此框架通常与 ASP.NET Core 配合使用[^4]。 ```csharp using Microsoft.Extensions.Logging; class Program { private readonly ILogger<Program> _logger; public Program(ILogger<Program> logger) { _logger = logger; } static void Main(string[] args) { var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); var program = new Program(loggerFactory.CreateLogger<Program>()); program.Run(); } void Run() { _logger.LogInformation("Application started."); _logger.LogWarning("This is a warning message."); _logger.LogError("An error occurred."); } } ``` #### 5. 自定义日志记录器 如果现有的日志库无法满足需求,开发者也可以创建自定义的日志记录器。这可以通过实现 `ILogger` 接口或直接编写文件操作代码来完成。 ```csharp using System.IO; class CustomLogger { public static void Log(string message) { File.AppendAllText("custom_log.txt", $"{message}{Environment.NewLine}"); } } CustomLogger.Log("This is a custom log message."); ``` ### 总结 C# 提供了多种日志记录方法和库,从简单的内置工具到功能强大的第三方库,开发者可以根据项目需求选择合适的解决方案。无论是轻量级的应用程序还是复杂的分布式系统,都可以找到适合的日志记录方案[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值