You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

日志文件中时间戳显示为格式字符串而非实际时间的问题排查求助

日志文件中时间戳显示为格式字符串而非实际时间的问题排查求助

我自己写了个日志工具,现在遇到了一个头疼的问题,想请教大家。

先给大家看看我的LogInfo方法代码:

public static void LogInfo(string message)
{
    if (!_settings.LogInfo) return;

    var timestamp = DateTime.Now.ToString();  // Default format if DateFormat is empty
    if (!string.IsNullOrEmpty(_settings.DateFormat))
    {
        try
        {
            timestamp = DateTime.Now.ToString(_settings.DateFormat);
        }
        catch
        {
            // If format is invalid, fall back to default format
            timestamp = DateTime.Now.ToString();
        }
    }
    var logEntry = new StringBuilder();
    logEntry.AppendLine($"[{timestamp}] INFO: {message}");
    logEntry.AppendLine("----------------------------------------");

    var fileName = _settings.SeparateLogFiles ? "info" : "combined";
    var logFile = Path.Combine(_settings.LogPath, $"{fileName}_{DateTime.Now:yyyy-MM-dd}.log");

    WriteToLog(logFile, logEntry.ToString());

    // Auto cleanup if enabled
    if (_settings.AutoCleanupLogs)
    {
        CleanupOldLogs();
    }
}

调用的时候就很简单:

Logger.LogInfo("App Started");

功能大体都是正常的,日志文件里能收到消息,但奇怪的是时间戳显示的是格式字符串,而不是实际的时间!比如日志内容是这样的:

[yyyy-MM-dd HH:mm:ss] INFO: Application started

我完全搞不懂为啥会出现这种情况。另外我的配置里的DateFormat根本不是这个格式(截图如下),也不知道这个yyyy-MM-dd HH:mm:ss是从哪冒出来的。

日志配置截图

还有个奇怪的点:如果我不在代码里加载配置的DateFormat,直接在代码里写死格式,就能正常显示真实的时间戳。

备注:内容来源于stack exchange,提问作者Johny Wave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 10:07:59