欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 简单日志帮助类LogHelper

程序员文章站 2022-05-03 15:06:22
调用: LogHelper.Debug(""); LogHelper.Info(""); LogHelper.Error(""); 项目添加LogHelper类 using System;using System.Collections.Generic;using System.IO;using S ......

调用:

loghelper.debug("");   

loghelper.info(""); 

loghelper.error("");

 

 

项目添加loghelper类

using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.text;

namespace avoidmisplace
{
public class loghelper
{
//在网站根目录下创建日志目录(bin文件夹→debug文件夹→logs文件夹)
public static string path = appdomain.currentdomain.basedirectory + "logs";

//死锁
public static object loglock = new object();

public static void debug(string content)
{
writelog("debug", content);
}

public static void info(string content)
{
writelog("info", content);
}

public static void error(string content)
{
writelog("error", content);
}

protected static void writelog(string type, string content)
{
lock (loglock)
{
if (!directory.exists(path))//如果日志目录不存在就创建
{
directory.createdirectory(path);
}

string time = datetime.now.tostring("yyyy-mm-dd hh:mm:ss:fff");//获取当前系统时间
string filename = path + "/" + datetime.now.tostring("yyyy-mm-dd") + ".log";//用日期对日志文件命名

//创建或打开日志文件,向日志文件末尾追加记录
streamwriter mysw = file.appendtext(filename);

//向日志文件写入内容
string write_content = time + " " + type + ": " + content;
mysw.writeline(write_content);

//关闭日志文件
mysw.close();
}
}
}
}