C# 簡單日志幫助類LogHelper


調用:

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();
}
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM