最简单的C#日志记录类

日常写代码经常要记录各种运行日志,网上开源的免费,功能强大的很多,但是有时候感觉为了写一个几百甚至几十行代码的小程序去下载一个“庞大的日志记录组建(xxlog.dll)”

不太值得,因此简单自己写一个类,使用简单,体积小!基本满足记录功能!

using Gaofajin.Attribute;

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.IO;

using System.Text;

namespace Gaofajin.LogWriter

{

/// <summary>

/// 日志记录到文件

/// </summary>

public class TxtLog

{

public string Dir { get; set; }

public string path { get; set; }

static TxtLog log = null;

static readonly object @lock = new object();

static System.Threading.ReaderWriterLockSlim Slim = new System.Threading.ReaderWriterLockSlim( System.Threading.LockRecursionPolicy.SupportsRecursion);

public static TxtLog Instance

{

get

{

if (log == null)

{

if (log == null)

{

lock (@lock)

{

log = new TxtLog();

}

}

}

return log;

}

}

private TxtLog()

{

}

/// <summary>

/// 写入日志到指定文件名

/// </summary>

/// <param name="Msg">要写到日志文件的信息</param>

public string WriteLineToFile(string Msg,LogType type)

{

if(string.IsNullOrEmpty(Dir)||Dir ==System.Windows.Forms.Application.StartupPath + @"\Logs\" + DateTime.Now.ToString("yyyy年MM月dd日"))

{

return WriteLineToTimeFile(Msg,type);

}

StreamWriter sw = null;

try

{

Slim.EnterWriteLock();

checkLog(Dir);

checkfile(Dir, path);

LogInfo li = GetLog(type);

string fileName = Dir + "\\" + path;

sw = File.AppendText(fileName);

sw.WriteLine("日志时间:" + DateTime.Now.ToString()+ ",文件名:" + li.FileName+ ",方法名:" + li.MethodName+ "行号:" + li.Line + ",列:" + li.Column+",日志类型:"+li.LogType);

sw.WriteLine("日志内容:" + Msg);

return nameof(WriteLineToFile) + "日志记录操作成功!";

}

catch(Exception ex)

{

return nameof(WriteLineToFile)+"日志记录操作错误:" +ex.Message;

}

finally

{

sw.Close();

Slim.ExitWriteLock();

}

}

/// <summary>

/// 在以小时为单位的文件名称里追加一行

/// </summary>

/// <param name="Msg">要写到日志文件的信息</param>

string WriteLineToTimeFile(string Msg,LogType type)

{

StreamWriter sw = null;

try

{

Slim.EnterWriteLock();

Dir = System.Windows.Forms.Application.StartupPath + @"\Logs\" + DateTime.Now.ToString("yyyy年MM月dd日");

checkLog(Dir);

string file = DateTime.Now.ToString("yyyy年MM月dd日HH时") + ".log";

checkfile(Dir, file);

string fileName = Dir + "\\" + file;

LogInfo li = GetLog(type);

sw = File.AppendText(fileName);

sw.WriteLine("日志时间:" + DateTime.Now.ToString() + ",文件名:" + li.FileName + ",方法名:" + li.MethodName + "行号:" + li.Line + ",列:" + li.Column + ",日志类型:" + li.LogType);

sw.WriteLine("日志内容:" + Msg);

return nameof(WriteLineToTimeFile)+"日志记录操作成功!";

}

catch(Exception ex)

{

return nameof(WriteLineToTimeFile) + "日志记录发生错误:" +ex.Message ;

}

finally

{

sw.Close();

Slim.ExitWriteLock();

}

}

//检查日志文件夹是否存在

void checkLog(string Path)

{

if (!Directory.Exists(Path))

{

Directory.CreateDirectory(Path);

}

}

/// <summary>

/// 传入路径名称和文件名称,创建日志文件

/// </summary>

/// <param name="DirName"></param>

/// <param name="FileName"></param>

void checkfile(string DirName,string FileName)

{

if (!File.Exists(DirName+@"\" + FileName ))

{

File.Create(DirName + @"\" + FileName ).Close();

}

}

public string SetLogFilePath(string logFilePath)

{

if (string.IsNullOrEmpty(logFilePath))

{

return nameof(SetLogFilePath) + "输入参数不能为空!";

}

Dir = logFilePath.Substring(0,logFilePath.LastIndexOf("\\"));

path = logFilePath.Substring(logFilePath.LastIndexOf("\\")+1,logFilePath.Length- logFilePath.LastIndexOf("\\")-1);

return nameof(SetLogFilePath)+"调用成功!";

}

internal struct LogInfo

{

internal string FileName { get; set; }

internal string MethodName { get; set; }

internal int Line { get; set; }

internal int Column { get; set; }

internal string LogType{get;set;}

}

internal LogInfo GetLog(LogType type)

{

StackTrace st = new StackTrace(2,true);

StackFrame sf = st.GetFrame(0);

LogInfo li = new LogInfo() {

FileName = sf.GetFileName(),

MethodName = sf.GetMethod().Name,

Line = sf.GetFileLineNumber(),

Column = sf.GetFileColumnNumber(),

};

string logType = "-Error";

switch (type)

{

case LogType.Error:

logType = "-Error";

break;

case LogType.Info:

logType = "-Info";

break;

case LogType.Waring:

logType = "-Waring";

break;

case LogType.Success:

logType = "-Success";

break;

case LogType.Failure:

logType = "-Failure";

break;

default:

logType = "-Error";

break;

}

li.LogType = logType;

return li;

}

}

}