JAMURILLO
JAMURILLO

Reputation: 41

Memory leak in Serilog

I have a Net6 worker service project. Use Serilog.ILogger for log errors on txt file but recently the memory usage increase (8GB) The worker only get data from Database with Dapper, return data and send mail. This is the versions

<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />

When catch exception of type SqlConnection and it´s regitry on log the memory usage increase, but when i have other type of exceptions this not happend.

 _logger.LogError("InterfaceLogsCleanerWorker executed with exceptions" + ex.Message);

this is the code for get data

public async Task<List<SetupDTO>> Get()
    {
        var map = new Sys_SetupMap();
        var result = new TransacResult(true, MessageTransactResult.OK);

        List<Sys_Setup> entityList;
        List<SetupDTO> list = new List<SetupDTO>();
        using (var conn = new SqlConnection(this.connectionString))
        {
            var parameters = new DynamicParameters();
            parameters.Add("Result", string.Empty, DbType.String, ParameterDirection.Output);

            entityList = (await conn.QueryAsync<Sys_Setup>("GetSys_Setup", parameters, commandType: CommandType.StoredProcedure)).AsList();
        }

        foreach (var entity in entityList)
        {
            list.Add(map.EntityToDTO(entity));
        }

        return list;
    }

Upvotes: 1

Views: 1545

Answers (1)

Ruben Bartelink
Ruben Bartelink

Reputation: 61795

This is due to how you are doing your log statement:

_logger.LogError("InterfaceLogsCleanerWorker executed with exceptions" + ex.Message);

This needs to be:

_logger.LogError(ex, "InterfaceLogsCleanerWorker executed with exceptions");

Or, worst case:

_logger.LogError("InterfaceLogsCleanerWorker executed with exceptions {message}",
                 ex.Message);

The docs cover this (the concept is that each message should be a message template - i.e. any given application should only have tens to thousands of message templates; and these get parsed and cached - in your code, everything you log (including the Message) is treated as a template)

The Serilog Analyzer can warn about usage mistakes like this: https://github.com/Suchiman/SerilogAnalyzer

Upvotes: -2

Related Questions