using System;
using System.IO;
namespace WebApplication2.Controllers
{
public static class LogExtentsions
{
private static string currentDay = string.Empty;//当前时间
private static object lockHelper = new object();//锁对象
/// <summary>
/// 延时初始化,文件路径
/// </summary>
private static Lazy<string> filePath = new Lazy<string>(delegate ()
{
//AppDomain.CurrentDomain:当前应用程序域
//AppDomain.CurrentDomain.BaseDirectory: 基目录,由程序集冲突解决程序用来探测程序集。
string tmpPath = AppDomain.CurrentDomain.BaseDirectory;
var path = Path.Combine(tmpPath, "Logs");//将两个字符串拼接成一个路径
if (!System.IO.Directory.Exists(path))//如果路径不存在
{
System.IO.Directory.CreateDirectory(path);//创建路径
}
return path;
}, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);//锁住进程,放置重复添加文件
public static string Prefix = string.Empty;
/// <summary>
/// 写入日志
/// </summary>
/// <param name="info">日志内容</param>
/// <param name="title">日志标题</param>
/// <param name="logpath">日志路径</param>
/// <param name="encoding">内容编码</param>
public static void WriteLine(string info, string title = null, string logpath = null, string encoding = null) {
if (string.IsNullOrWhiteSpace(info))//判断内容是否为空,如果为空就直接返回
{
return;
}
var tmpDay = DateTime.Now.ToString("yyyyMMdd");//当前时间转年月日字符串
var tmpPath = Path.Combine(filePath.Value, tmpDay);//拼接路径,当前应用程序路径加上+logs,+年月日
if (Directory.Exists(tmpPath)==false)//目录不存在
{
Directory.CreateDirectory(tmpPath);//创建目录
}
//var isTitleEmpty = string.IsNullOrWhiteSpace(title);//日志标题是否为空
string logfilepath;
var logFileName = "";
//if (isTitleEmpty)//如果日志标题为空,则目录拼接年月日.log
//{
// logfilepath = Path.Combine(tmpPath, Prefix + tmpDay + ".log");
//}
//else {
// logfilepath = Path.Combine(tmpPath, title + ".log");//用户传了目录信息则在年月日目录下面创建标题.log文件
//}
//如果标题字段有内容则标题.log,如果标题字段没有内容则日期+log
logFileName = (title == null ? "" : title) == "" ? (tmpDay + ".log") : title + ".log";
if (!string.IsNullOrWhiteSpace(logpath))
{
var logpathSrc = Path.Combine(tmpPath,logpath);//拼接用户传进来的目录
if (!Directory.Exists(logpathSrc))//如果用户传进来的目录不存在
{
Directory.CreateDirectory(logpathSrc);
}
logfilepath = Path.Combine(tmpPath, logpath, logFileName);//拼接应用程序日志路径,用户自定义路径,文件名称
}
else {
logfilepath = Path.Combine(tmpPath, logFileName);
}
var tmpText = string.Concat(DateTime.Now.ToString(), ":", "\r\n", info.ToString());//内容拼接,时间:换行,用户传的信息
var tmpLogInfo = new string[] { logfilepath, tmpText, encoding };
lock (lockHelper)//锁住线程
{
try
{
//tmpLogInfo[0]-logfilepath路径,FileMode.Append:如果目录文件存在则追加,否则创建文件,FileAccess.Write:文件写权限
using (FileStream fileStream=new FileStream(tmpLogInfo[0],FileMode.Append,FileAccess.Write))
{
if (!string.IsNullOrWhiteSpace(tmpLogInfo[2]))
{
using (StreamWriter streamWrite = new StreamWriter(fileStream, System.Text.Encoding.GetEncoding(tmpLogInfo[2])))
{
streamWrite.WriteLine(tmpLogInfo[1]);
streamWrite.WriteLine();
streamWrite.Flush();//清理当前写入器的所有缓冲区,并使所有缓冲数据写入基础流。
}
}
else {
using (StreamWriter streamWrite = new StreamWriter(fileStream))
{
streamWrite.WriteLine(tmpLogInfo[1]);
streamWrite.WriteLine();
streamWrite.Flush();//清理当前写入器的所有缓冲区,并使所有缓冲数据写入基础流。
}
}
}
}
catch (Exception ex)
{
// 异常:
// T:System.ObjectDisposedException:
// 当前编写器已关闭。
//
// T:System.IO.IOException:
// 发生了 I/O 错误。
//
// T:System.Text.EncoderFallbackException:
// 当前编码不支持显示半个 Unicode 代理项对。
Console.WriteLine("录入日志异常:" + ex.Message);
}
}
}
}
}