需求:程序启动后到关闭,只新建一个Log文件,所有的Log内容都在一个文件中。
注意:为了避免Log内容错乱,使用Dispatcher调度
Log
Log.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Log
{
public delegate string BuildMessage();
public class Log
{
private static string DLL_PATH = "DebugLog.dll";
private static string OUTPUT_PATH = "";
private static ILog _iLog = null;
private static bool _isNeedLog = false;
static Log()
{
try
{
if (InitConfigSettings())
{
var type = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + DLL_PATH).GetTypes()?.Single((T) => T.GetInterface(nameof(ILog)) != null);
object[] parameters = new object[] { OUTPUT_PATH };
_iLog = (ILog)Activator.CreateInstance(type, parameters);
}
}
catch
{
}
}
public static void Write(string message)
{
if (_iLog != null)
{
try
{
if(FilterLog())
{
_iLog.Write(message);
}
}
catch(Exception ex)
{
_iLog.Write(ex.StackTrace.ToString());
}
}
}
public static void Wirte(BuildMessage messageAction)
{

本文档介绍了如何通过单例模式配合Dispatcher来确保程序运行期间仅创建一个Log文件,并统一管理所有日志输出,防止内容错乱。涉及关键类包括Log.cs、ILog.cs、DebugLog和DebugLogWrite.cs,以及配置文件App.config。
最低0.47元/天 解锁文章
746

被折叠的 条评论
为什么被折叠?



