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

.NET Aspire中清理旧日志以解决系统卡顿问题

解决.NET Aspire中OpenTelemetry日志堆积导致系统卡顿的问题

针对你遇到的日志堆积(两天8000条)导致系统卡顿的问题,结合你的OpenTelemetry配置,提供以下几种解决方案:

一、从源头减少日志生成(优先推荐)

过多的日志不仅会占用存储,还会增加系统IO开销,先通过日志过滤减少不必要的日志输出:

builder.Logging.AddOpenTelemetry(o =>
{
    o.AddOtlpExporter();
    o.IncludeFormattedMessage = true;
    o.IncludeScopes = true;
})
// 过滤框架级别的冗余日志,只保留Warning及以上
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
// 自定义API服务保留Info及以上级别,可根据需求调整
.AddFilter("sinamn75api", LogLevel.Information);

二、配置Aspire Dashboard日志保留策略

如果日志存储在Aspire默认的SQLite数据库中,可在Aspire的AppHost项目里设置日志保留天数,自动清理旧日志:

var builder = DistributedApplication.CreateBuilder(args);

// 配置日志数据库的保留策略,示例为保留7天内的日志
var logsDb = builder.AddSqlite("logsdb")
    .WithVolume("./aspire-logs", "/data")
    .WithEnvironment("ASPIRE_LOG_RETENTION_DAYS", "7");

// 将你的API服务关联到日志数据库
var apiService = builder.AddProject<Projects.sinamn75api>("sinamn75api")
    .WithReference(logsDb);

builder.Build().Run();

三、自定义定时清理服务

如果需要更灵活的清理逻辑(比如按日志级别、特定内容清理),可以实现一个后台定时服务来清理旧日志:

public class LogCleanupService : BackgroundService
{
    private readonly IConfiguration _config;
    // 每天执行一次清理
    private readonly TimeSpan _cleanupInterval = TimeSpan.FromHours(24);

    public LogCleanupService(IConfiguration config)
    {
        _config = config;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await CleanupExpiredLogs(stoppingToken);
            await Task.Delay(_cleanupInterval, stoppingToken);
        }
    }

    private async Task CleanupExpiredLogs(CancellationToken cancellationToken)
    {
        var connStr = _config.GetConnectionString("logsdb");
        if (string.IsNullOrWhiteSpace(connStr)) return;

        await using var conn = new SqliteConnection(connStr);
        await conn.OpenAsync(cancellationToken);

        // 删除7天前的所有日志,可根据需求调整时间范围或过滤条件
        var cmd = conn.CreateCommand();
        cmd.CommandText = "DELETE FROM Logs WHERE Timestamp < datetime('now', '-7 days')";
        await cmd.ExecuteNonQueryAsync(cancellationToken);
    }
}

// 在Program.cs中注册该后台服务
builder.Services.AddHostedService<LogCleanupService>();

四、OtlpExporter后端的清理配置

如果你的日志是通过OtlpExporter发送到第三方后端(如Elasticsearch、Jaeger),需要在对应后端配置自动清理:

  • Elasticsearch:配置索引生命周期管理(ILM),设置自动删除超过保留期的索引
  • Jaeger:修改配置文件中的span-storage.type和对应存储的保留参数(如Cassandra的ttl)
  • Prometheus:在配置文件中设置retention.time参数指定数据保留时长

内容的提问来源于stack exchange,提问作者SinaMN75

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:47:25