Unity中日志系统的配置与使用
Unity日志系统是游戏开发过程中非常重要的工具,它可以帮助开发者追踪和诊断问题。以下是关于Unity.Logging包的配置和使用方法的详细说明。
基本配置
Unity.Logging是Unity提供的日志系统,它提供了比Debug.Log更丰富的功能。下面是一个基本的配置示例:
using System;
using System.IO;
using Unity.Logging;
using Unity.Logging.Sinks;
using UnityEngine;
public class UnityLoggingTest : MonoBehaviour
{
    void Start()
    {
        // 基础路径配置
        string basePath = Application.isEditor ? 
            Path.GetFullPath(Path.Combine(Application.dataPath, "..")) : 
            Application.persistentDataPath;
        
        // 创建日志目录
        string logsFolder = Path.Combine(basePath, "Logs");
        if (!Directory.Exists(logsFolder)) 
            Directory.CreateDirectory(logsFolder);
        
        // 生成带时间戳的文件名
        string timestamp = DateTime.Now.ToString("yyyyMMdd-HH_mm_ss");
        string logFileName = $"log-{timestamp}.txt";
        
        // 完成日志路径
        string fullLogPath = Path.Combine(logsFolder, logFileName);
        
        // 配置日志系统
        Log.Logger = new Unity.Logging.Logger(new LoggerConfig()
            .MinimumLevel.Debug()
            .OutputTemplate("[{Timestamp} {Level}] {Message}{NewLine}{Stacktrace}")
            .WriteTo.File(fullLogPath)
            .WriteTo.UnityEditorConsole(outputTemplate: "{Message}{NewLine}{Stacktrace}"));
            
        // 记录不同级别的日志
        Log.Info("这是一条信息日志");
        Log.Debug("这是一条调试日志");
        Log.Warning("这是一条警告日志");
        Log.Error("这是一条错误日志");
        Log.Fatal("这是一条致命错误日志");
    }
    
    void Update()
    {
        // 可以在这里添加需要每帧执行的日志记录
    }
}
关键点说明
1. 路径设置
- 在编辑器模式下,日志保存在项目根目录的Logs文件夹中
- 在运行时,日志保存在Application.persistentDataPath下的Logs文件夹中
2. 日志文件命名
- 使用时间戳格式化为yyyyMMdd-HH_mm_ss,确保每次运行都生成新的日志文件
- 文件命名格式为log-{timestamp}.txt
3. 日志配置
- MinimumLevel.Debug():设置最低记录日志级别为Debug
- OutputTemplate:定义日志输出格式,包含时间戳、日志级别、消息内容和堆栈跟踪
- WriteTo.File():Use- LoggerConfig.WriteTo.Fileto use a file sink. This is the easiest way to capture logs. The file contains each log entry on a single line and is readable through any text editor.
- writeTo.JsonFile: Use- LoggerConfig.WriteTo.JsonFileto capture the logs into a JSON line file. Every line is a parsable JSON object where the output template defines each key. This is a useful format when the logs are large and if you want to filter the data to find specific information. It's also useful for server and cloud environments where dedicated tools use the log files for filtering and parsing capabilities.
- WriteTo.UnityEditorConsole():将日志输出到Unity编辑器控制台
4. 日志级别
Unity.Logging提供了五种日志级别,从低到高依次为:
- Debug:调试信息
- Info:一般信息
- Warning:警告信息
- Error:错误信息
- Fatal:致命错误
最佳实践
- 
根据环境调整日志级别: #if DEVELOPMENT_BUILD || UNITY_EDITOR .MinimumLevel.Debug() #else .MinimumLevel.Warning() #endif
- 
在重要流程中添加日志点: - 游戏启动和关闭
- 场景加载
- 玩家重要操作
- 网络请求和响应
- 资源加载和卸载
 
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号