Registro inteligente con Serilog en .NET

Descubre Serilog en .NET: registros estructurados, control dinámico de niveles, API de gestión y sinks personalizados (incluido AWS SNS) para monitoreo eficiente sin redeploy.

8 sept 2025 • 5 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

El registro es mucho más que escribir mensajes en un archivo es el sistema nervioso de tu aplicación. Te dice qué salió mal cuándo y a menudo por qué. En sistemas en producción, el registro se convierte en una línea de vida para diagnosticar problemas rastrear el comportamiento de los usuarios y mantener la claridad operativa.

Pero registrar no se trata solo de volumen se trata de control. Muy poco te deja a ciegas. Demasiado te sumerge en ruido.

En Serilog, una biblioteca de registro estructurado para .NET que aporta claridad flexibilidad y poder a tu estrategia de registro. A diferencia de registradores tradicionales Serilog trata los logs como datos enriquecidos no solo cadenas lo que facilita filtrarlos consultararlos y enrutar a múltiples destinos.

Serilog ofrece:

Registro estructurado con propiedades nombradas

Sinks flexibles para escribir logs en archivos en consola bases de datos servicios en la nube y más

Control en tiempo real sobre los niveles de registro

Filtrado personalizado para evitar inundar sistemas externos

Extensibilidad para integrar tus propios sinks

Ya sea que estés depurando una característica inestable o monitoreando errores críticos en producción en este artículo exploraremos cómo lograr control sobre Serilog sin volver a desplegar ni reiniciar tu aplicación.

Utilizando las características anteriores de Serilog exploraremos cómo:

Controlar dinámicamente el nivel de log de Serilog en tiempo de ejecución usando LoggingLevelSwitch

Exponer el control de nivel de log mediante un panel de administración o API

Auto-elevación de logging durante excepciones y revertir tras un tiempo

Enviar logs filtrados a AWS SNS mediante una sink personalizada

Control de Nivel de Registro en Tiempo de Ejecución

Comencemos configurando Serilog en la aplicación

Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();

var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Error); builder.Services.AddSingleton(levelSwitch);

Log.Logger = new LoggerConfiguration().MinimumLevel.ControlledBy(levelSwitch).WriteTo.Console().WriteTo.File(logs/log.txt).CreateLogger();

levelSwitch.MinimumLevel = LogEventLevel.Information;

Exponiendo el control de nivel de log mediante API

Sabiendo que ya contamos con un switch, podemos usar o exponerlo mediante una API para invocarlo directamente o desde un panel administrativo

[ApiController] [Route(api/logging)]

public class LoggingController : ControllerBase { private readonly LoggingLevelSwitch _levelSwitch; public LoggingController(LoggingLevelSwitch levelSwitch) { _levelSwitch = levelSwitch; } [HttpPost(set-level)] public IActionResult SetLevel([FromQuery] string level) { _levelSwitch.MinimumLevel = Enum.Parse<LogEventLevel>(level, true); return Ok(Log level set to {level}); } }

Log Level Control from Admin Dashboard

La API anterior puede ser invocada desde un panel de administración o desde una interfaz frontend

Abrir desplegable de selección

<select onChange={e => setLogLevel(e.target.value)}> <option value=Error>Error</option> <option value=Information>Information</option> <option value=Debug>Debug</option></select>

API Call

const setLogLevel = async level => { fetch(/api/logging/set-level?level=${level}, { method: post }); }

Esto permitirá a tu equipo tener control en tiempo real sobre la verbosidad de los registros sin necesidad de redeploys.

Auto-Elevate Logging on Exceptions

No solo vía API también podemos usar el switch de nivel de registro de forma silenciosa en nuestra app por ejemplo ante una excepción fatal. Vamos a usar el switch en el manejador global de excepciones de la app

public class GlobalExceptionMiddleware { private readonly RequestDelegate _next; private readonly LoggingLevelSwitch _levelSwitch; public GlobalExceptionMiddleware(RequestDelegate next, LoggingLevelSwitch levelSwitch) { _next = next; _levelSwitch = levelSwitch; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { _levelSwitch.MinimumLevel = LogEventLevel.Information; Log.Error(ex, Unhandled exception occurred) Log.Information(Log level elevated to Info) _ = Task.Delay(TimeSpan.FromMinutes(5)).ContinueWith(_ => { Log.Information(Log level reverted to Error) _levelSwitch.MinimumLevel = LogEventLevel.Error; }); context.Response.StatusCode = 500; await context.Response.WriteAsync Something went wrong. } } }

Note: El Log.Information debe ir antes de volver a establecer el nivel a Error para que se emita.

No olvides registrar el middleware

app.UseMiddleware<GlobalExceptionMiddleware>()

¿Cómo puede la elevación del nivel de registro ayudar a depurar ?

Podemos usar Log.Information en diferentes puntos de nuestra app para la trazabilidad, pero el nivel de registro establecido en Error no emitirá estos mensajes hasta que cambiemos el nivel. Entonces estos mensajes informativos en los registros nos ayudarán a averiguar dónde se rompió algo especialmente en trabajos en segundo plano.

Setting up and using a Custom Sink

Sinks son cualquier destino al que quieras que Serilog envíe logs pueden ser un archivo una cola de mensajes o algún servicio de notificaciones en la nube. En nuestro ejemplo crearemos un sink que envíe logs a un tema AWS SNS.

public class AwsSnsSink : ILogEventSink { private readonly IAmazonSimpleNotificationService _snsClient; private readonly string _topicArn; public AwsSnsSink(IAmazonSimpleNotificationService snsClient, string topicArn) { _snsClient = snsClient; _topicArn = topicArn; } public void Emit(LogEvent logEvent) { var message = logEvent.RenderMessage(); _snsClient.PublishAsync(new PublishRequest { TopicArn = _topicArn, Message = ${logEvent.Timestamp}: ${logEvent.Level} - ${message} }); } }

Registra el sink en Program.cs y añádelo a la configuración de Serilog

builder.Services.AddAWSService<IAmazonSimpleNotificationService>(); builder.Services.AddSingleton(levelSwitch); var snsClient = builder.Services.BuildServiceProvider().GetRequiredService<IAmazonSimpleNotificationService>(); var topicArn = builder.Configuration[AWS:SnsTopicArn]; Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Console() .WriteTo.File(logs/log.txt) .WriteTo.Sink(new AwsSnsSink(snsClient, topicArn)) .CreateLogger();

Asegúrate de que tus credenciales y región de AWS estén configuradas a través de variables de entorno o appsettings.json

Filtrado para evitar inundar SNS

Ahora que tenemos un sink personalizado para recibir logs debemos tener cuidado con el costo y no saturar el tema. Demasiado ruido también sale caro.

Podemos modificar el método Emit de la clase sink

public void Emit(LogEvent logEvent) { if (logEvent.Level < LogEventLevel.Warning) return; // continuar enviando }

O podemos añadir el filtro en la configuración de Serilog en Program.cs

... .WriteTo.Logger(lc => lc .Filter.ByIncludingOnly(le => le.Level >= LogEventLevel.Warning) WriteTo.Sink(new AwsSnsSink(snsClient, topicArn)) ...

Esto garantiza que solo Warning, Error y Fatal lleguen a SNS manteniendo esta opción rentable y la canalización en la nube eficiente y significativa.

Conclusión

Con LoggingLevelSwitch de Serilog obtienes control en tiempo de ejecución sobre la verbosidad de los registros. Combínalo con sinks personalizados y filtrado inteligente y tendrás un pipeline de registro que es fácil para el desarrollo y seguro para la producción.

Ya sea que estés enviando logs a servicios cloud aws y azure o a un panel como Power BI para observabilidad e inteligencia de negocio, esta arquitectura te ofrece la flexibilidad para observar depurar y escalar sin ahogarte en ruido de logs. En IA para empresas y en proyectos de aplicaciones a medida de Q2BSTUDIO encontrarás soluciones que combinan inteligencia artificial ciberseguridad y servicios en la nube para impulsar tu negocio. En Q2BSTUDIO somos una empresa de desarrollo de software especializada en aplicaciones a medida y automatización de procesos con experiencia en ciberseguridad IA para empresas y servicios inteligencia de negocio. Si buscas potenciar tu negocio con inteligencia artificial agentes IA y power bi para mejorar tu posicionamiento web en relación a esas palabras clave, contáctanos para una consulta inicial y descubre cómo una solución de registro inteligente con Serilog puede integrarse con tu estrategia de software a medida y soluciones en la nube

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat