游戏运行之时打印日志,方便我们查bug,下面我说说自己项目的日志系统怎么弄。
日志等级分别为
LogLevel.DEBUG,
LogLevel.INFO,
LogLevel.WARNING,
LogLevel.ERROR,
LogLevel.CRITICAL,
LogLevel.EXCEPT。
//获得类名和方法名
private static String GetStackInfo()
{
StackTrace st = new StackTrace();
StackFrame sf = st.GetFrame(2);//
var method= sf.GetMethod();
return String.Format("{0}.{1}():",method.ReflectedType.Name,method.Name);
}
解析:
我们在学习函数调用时,都知道每个函数都拥有自己的栈空间。一个函数被调用时,就创建一个新的栈空间。那么通过函数的嵌套调用最后就形成了一个函数调用堆栈。在c#中,使用StackTrace记录这个堆栈。你可以在程序运行过程中使用StackTrace得到当前堆栈的信息。
日记类LoggerHelper
分别有几个接口:
LoggerHelper.Debug(string filter, object message, Boolean isShowStack = SHOW_STACK);
LoggerHelper.Info(string filter, object message, Boolean isShowStack = SHOW_STACK);
LoggerHelper.Warning(string filter, object message, Boolean isShowStack = SHOW_STACK);
LoggerHelper.Error(string filter, object message, Boolean isShowStack = SHOW_STACK);
LoggerHelper.Critical(string filter, object message, Boolean isShowStack = SHOW_STACK);
LoggerHelper.Except(string filter, object message, Boolean isShowStack = SHOW_STACK);
统一调用
Log(string message,LogLevel level ,bool writeEditorLog = ture)
{
var msg = string.Concat(DataTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff"),message);
m_logWriter.WriteLog(msg,level,writeEditorLog);
}
如:Log(string.Concat("[DEBUG]:",isShowStack?GetStackInfo():"",message,"Index = ",index++),LogLevel.DEBUG);
public class LogWriter
{
private string m_logPath = UnityEngine.Application.persistentDtaPath + "/log/";
private string m_logFileName = "log_{0}.txt";
private string m_logFilePath;
private FileStream m_fs;
private StreamWriter m_sw;
private Action<String,LogLevel,bool> m_logWriter;
private readonly static object m_locker = new object();
public LogWriter()
{
if(Directory.Exists(m_logPath)) Directory.CreateDirectory(m_logPath);
m_logFilePath = String.Concat(m_logPath,String.Format(m_logFileName,DataTime.Today.ToString("yyyyMMdd"));
try
{
m_logWriter = Write;
m_fs = new FileStream(m_logFilePath,FileMode.Append,FileAccess.Write,FileShare.ReadWrite);
m_sw = new StreamWriter(m_fs)
}
catch{}
//释放资源
public void Release()
{
lock(m_locker)
{
if(m_sw != null)
{
m_sw.Close();
m_sw.Dispose();
.....
}
private void Write(string msg,LogLevel level,bool writeEditorLog)
{
lock(m_locker)
try
{
if(m_sw != null)
{
m_sw.WriteLine(msg);
m_sw.Flush();
}
.....
}
}