using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WCS.BLL.Config;
using WCS.DAL;
using WCS.Model;
namespace WCS.BLL
{
///
/// 日志类型
///
public enum LogsType
{
///
/// 信息
///
Info,
///
/// 警告
///
Warning,
///
/// 错误
///
Err,
///
/// 数据库错误
///
DbErr,
}
///
/// 日志
///
public static class Logs
{
static object obj = new object();
const string logExtension = ".log";
///
/// 写入日志失败
///
public static Action, DateTime, LogsType, Exception> WriteErr = null;
///
/// 写入日志
///
/// 内容
/// 类型
/// 是否写入成功
public static void Write(IEnumerable content, LogsType type = LogsType.Info)
{
if (content == null || !content.Any())
return;
var dt = DateTime.Now;
string hms = dt.ToString("HH:mm:ss.fff");
List lines = new List(content.Count());
try
{
string path = Path.Combine(Config.LocalFile.LogDir, type.ToString(), $"{(dt.ToString("yyyyMMdd"))}{logExtension}");
foreach (var item in content)
lines.AddRange($"[{hms}]{item}".Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
lock (obj)
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.AppendAllLines(path, lines, Encoding.UTF8);
}
}
catch (Exception ex)
{
WriteErr?.Invoke(content, dt, type, ex);
}
}
///
/// 写入日志
///
/// 内容对象
/// 类型
/// 是否写入成功
public static void Write(string content, LogsType type = LogsType.Info)
{
Write(new string[] { content }, type);
}
///
/// 写入日志
///
/// 内容对象
/// 类型
/// 是否写入成功
public static void Write(object content, LogsType type = LogsType.Info)
{
Write(JsonConvert.SerializeObject(content), type);
}
///
/// 写入日志
///
/// 内容
/// 内容标题
/// 类型
/// 是否写入成功
public static void Write(object content, string contentTitle, LogsType type = LogsType.Info)
{
Write($"{contentTitle} {JsonConvert.SerializeObject(content)}", type);
}
///
/// 写入日志
///
/// 错误
/// 是否写入成功
public static void Write(Exception ex, LogsType type = LogsType.Err)
{
Write(ex.ToString(), type);
}
///
/// 清除日志
///
/// 保留时间
/// 清理的大小(字节)
public static long Clear(TimeSpan time)
{
long size = 0;
var rs = EnumHelps.GetEnumList(typeof(LogsType));
foreach (var item in rs)
{
try
{
var path = Path.Combine(Config.LocalFile.LogDir, item);
DirectoryInfo directoryInfo = new DirectoryInfo(path);
if (!directoryInfo.Exists)
continue;
var files = directoryInfo.GetFiles($"**{logExtension}", SearchOption.TopDirectoryOnly);
var fileDel = files.Where(o => o.CreationTime < (DateTime.Now - time));
foreach (var item2 in fileDel)
{
size += item2.Length;
item2.Delete();
}
}
catch (Exception)
{
}
}
return size;
}
}
}