C# 简单日志实现
1、
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ChangesStatistics.Helper
{
public class LogHelper
{
private static object locked = new object();
private static readonly string DirectoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
public static void Error(string fileName, Exception ex)
{
Error(fileName, "异常原因:" + ex.Message + Environment.NewLine + "异常位置:" + ex.StackTrace);
}
public static void Error(string fileName, string content ,Exception ex)
{
Error(fileName, content + Environment.NewLine + "异常原因:" + ex.Message + Environment.NewLine + "异常位置:" + ex.StackTrace);
}
public static void Error(string fileName, string content)
{
if (Environment.UserInteractive)
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Error:" + content);
if (!Directory.Exists(DirectoryPath))
Directory.CreateDirectory(DirectoryPath);
lock (locked)
{
File.AppendAllText(
Path.Combine(DirectoryPath, fileName + "(" + DateTime.Now.ToString("yyyy-MM-dd") + "Error).txt"),
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + content + Environment.NewLine + Environment.NewLine, Encoding.UTF8);
}
}
public static void Info(string fileName, string content)
{
if (Environment.UserInteractive)
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Info:" + content);
if (!Directory.Exists(DirectoryPath))
Directory.CreateDirectory(DirectoryPath);
lock (locked)
{
File.AppendAllText(
Path.Combine(DirectoryPath, fileName + "(" + DateTime.Now.ToString("yyyy-MM-dd") + "Info).txt"),
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + content + Environment.NewLine + Environment.NewLine, Encoding.UTF8);
}
}
}
}
2、
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
namespace Dos.Common
{
/// <summary>
/// 日志帮助类。AppSettings节点可以配置Dos.LogHelper.Debug=0或Dos.LogHelper.Error=0来关闭日志记录。
/// 如果不传入path参数,默认是在~/Log/下生成日志文件,也可以在AppSettings节点配置Dos.LogHelper.Path来设置默认日志文件路径,格式:D:\\File\\Log\\。
/// </summary>
public class LogHelper
{
private static readonly object Olock = new object();
private enum LogHelperType
{
debug, error
}
/// <summary>
/// 记录调试日志
/// </summary>
/// <Param name="content">内容。如需换行可使用:\r\n</Param>
/// <Param name="filePrefixName"></Param>
/// <Param name="path">格式:D:\\File\\Logs\\</Param>
public static void Debug(string content, string filePrefixName = null, string path = null)
{
Write(LogHelperType.debug, content, filePrefixName, path);
}
/// <summary>
/// 记录错误日志
/// </summary>
/// <Param name="content">内容。如需换行可使用:\r\n</Param>
/// <Param name="filePrefixName"></Param>
/// <Param name="path">格式:D:\\File\\Logs\\</Param>
public static void Error(string content, string filePrefixName = null, string path = null)
{
Write(LogHelperType.error, content, filePrefixName, path);
}
/// <summary>
/// filePrefixName是文件名前缀,最好用中文,方便在程序Logs文件下查看。
/// </summary>
/// <Param name="content">内容。如需换行可使用:\r\n</Param>
/// <Param name="filePrefixName"></Param>
/// <Param name="path"></Param>
/// <Param name="logtype"></Param>
private static void Write(LogHelperType logtype, string content, string filePrefixName = null, string path = null)
{
lock (Olock)
{
try
{
if (logtype == LogHelperType.debug)
{
var dosDebug = ConfigurationManager.AppSettings["Dos.LogHelper.Debug"];
if (dosDebug != null && dosDebug != "1")
{
return;
}
}
else
{
var dosError = ConfigurationManager.AppSettings["Dos.LogHelper.Error"];
if (dosError != null && dosError != "1")
{
return;
}
}
#region 日志文件
var fileName = filePrefixName + DateTime.Now.ToString("yyyyMMdd") + logtype.ToString() + ".txt";
if (string.IsNullOrWhiteSpace(path))
{
var dosPath = ConfigurationManager.AppSettings["Dos.LogHelper.Path"];
if (string.IsNullOrWhiteSpace(dosPath))
{
path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + fileName;
}
else
{
path = dosPath + fileName;
}
}
else
{
path += fileName;
}
var di = new DirectoryInfo(path.Replace(fileName, ""));
if (!di.Exists)
{
di.Create();
}
//判断文件大小,需要新开文件
using (var fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
var sw = new StreamWriter(fs);
sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine();
sw.Write(content);
sw.WriteLine();
sw.Write("-----------------------------------------------------------------------------");
sw.WriteLine();
sw.Flush();
sw.Close();
}
#endregion
}
catch
{
}
}
}
}
}
分类:
.NET
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器