引用
using System;
using System.IO;
using System.Text;
代码类
public static class LogHelper
{
private const int LOG_CONTENT_MAX_LENGTH = 800;
static LogHelper()
{
string logDirPath = Path.Combine(Directory.GetCurrentDirectory(), "Log");
if (!Directory.Exists(logDirPath))
{
Directory.CreateDirectory(logDirPath);
}
}
private static string GetCurrentLogExistsPath()
{
string logPath = Path.Combine(Directory.GetCurrentDirectory(), "Log", DateTime.Now.ToString("yyyy-MM-dd") + ".log");
if (!File.Exists(logPath))
{
File.Create(logPath).Close();
}
return logPath;
}
public static void Debug(string text)
{
WriteLog(logLevel.Debug, text);
}
public static void Error(string text)
{
WriteLog(logLevel.Error, text);
}
public static void Info(string text)
{
WriteLog(logLevel.Info, text);
}
private static void WriteLog(logLevel label, string log_content)
{
if (log_content.Length > LOG_CONTENT_MAX_LENGTH)
{
log_content = log_content.Substring(0, LOG_CONTENT_MAX_LENGTH);
}
var logPath = GetCurrentLogExistsPath();
using (var fs = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
fs.Position = fs.Length;
byte[] bytes = Encoding.UTF8.GetBytes($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {label} {log_content}{Environment.NewLine}");
fs.Write(bytes, 0, bytes.Length);
}
}
public enum logLevel
{
Debug = 0,
Info = 1,
Error = 2
}
}
调用方法
//一般日志
LogHelper.Info("程序启动!");
//错误日志
LogHelper.Error("发生异常:" + ex.ToString());