using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
/// <summary>
/// 打印日志
/// </summary>
/// <param name="obj"></param>
public static void WriteLog(object obj)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
try
{
using (StreamWriter sw = File.AppendText(logPath))
{
string msg = string.Join("*****", obj);
sw.WriteLine("消息:" + msg);
sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine();
sw.Flush();
sw.Close();
sw.Dispose();
}
}
catch (IOException e)
{
using (StreamWriter sw = File.AppendText(logPath))
{
sw.WriteLine("异常:" + e.Message);
sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
sw.WriteLine();
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
static void Main(string[] args)
{
WriteLog(JsonConvert.SerializeObject(new string[] { "1", "2" }));
}
}
}
C# 简单日志的实现
最新推荐文章于 2023-11-27 09:53:23 发布