Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Products
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. CWE-532: Secure Logging in ASP.NET Core - Avoiding Sensitive Data in Logs with Serilog

CWE-532: Secure Logging in ASP.NET Core - Avoiding Sensitive Data in Logs with Serilog

Date- Jun 07,2026 246
cwe 532 secure logging

Overview

The CWE-532 classification addresses the issue of logging sensitive information in applications, which can lead to severe security vulnerabilities. In the context of ASP.NET Core, developers often encounter scenarios where logging is essential for monitoring and debugging, yet inadvertently log sensitive data such as passwords, credit card numbers, or personal identification information. This not only exposes the application to risks such as data breaches but also violates data protection regulations like GDPR or HIPAA.

Secure logging practices help developers maintain the integrity and confidentiality of sensitive information while still capturing critical application behavior. Real-world use cases include e-commerce platforms that handle customer transactions, healthcare applications managing patient data, and any system where user privacy is paramount. By adopting secure logging strategies, developers can ensure that their applications remain compliant and secure.

Prerequisites

  • ASP.NET Core knowledge: Familiarity with the ASP.NET Core framework and its middleware.
  • Serilog library: Basic understanding of Serilog and how to integrate it into an ASP.NET Core application.
  • C# programming: Proficiency in C# to effectively implement logging strategies.
  • NuGet package management: Experience with managing dependencies using NuGet.

Setting Up Serilog in ASP.NET Core

To begin using Serilog for logging in an ASP.NET Core application, you must first install the Serilog packages via NuGet. Serilog is a powerful and flexible logging library that supports structured logging, which is essential for identifying sensitive data in logs.

dotnet add package Serilog.AspNetCore

This command installs the Serilog.AspNetCore package, which provides middleware to integrate Serilog into the ASP.NET Core logging pipeline. After installation, you can configure Serilog in the Program.cs file of your ASP.NET Core application.

using Serilog;

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.Console()
            .CreateLogger();

        try
        {
            Log.Information("Starting up the application...");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Application start-up failed");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
        .UseSerilog() // Integrate Serilog
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup();
        });
}

This example configures Serilog to log messages with a minimum level of Debug and writes log output to the console. The UseSerilog() method integrates Serilog into the ASP.NET Core pipeline, replacing the default logging system.

Understanding the Logger Configuration

In the configuration, MinimumLevel.Debug() sets the threshold for log messages, ensuring that all messages of Debug level and higher are captured. The WriteTo.Console() method specifies that log messages should be output to the console, which is useful during development. The CreateLogger() method finalizes the logger configuration.

Implementing Secure Logging Practices

To avoid logging sensitive information, it is crucial to implement secure logging practices. One effective way to achieve this is by using Serilog's filtering capabilities to exclude specific properties or values from being logged.

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console()
    .Enrich.FromLogContext()
    .Filter.ByExcluding(Matching.WithProperty("Password")) // Exclude Password
    .CreateLogger();

In this configuration, the Filter.ByExcluding() method is used to prevent any log entries that contain the Password property from being logged. This ensures that sensitive information is not inadvertently exposed in log files.

Advanced Filtering Techniques

In addition to excluding specific properties, Serilog supports more complex filtering rules. You can use the Matching.WithProperty() method to create conditions based on the values of properties.

.Filter.ByExcluding(Matching.WithProperty("CreditCardNumber", "1234-5678-9876-5432")) // Exclude specific credit card number

This example shows how to filter out a specific credit card number from the logs. However, a better approach would be to exclude all credit card numbers dynamically. This can be achieved using a regex pattern or by implementing a custom log enrichment.

Custom Enrichment for Sensitive Data

Custom enrichment allows developers to dynamically modify log entries before they are written, providing a powerful tool for secure logging. You can create an enrichment class that checks for sensitive data patterns and masks or removes them.

public class SensitiveDataEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory factory)
    {
        if (logEvent.Properties.ContainsKey("Password"))
        {
            logEvent.AddOrUpdateProperty(factory.CreateProperty("Password", "[REDACTED]"));
        }
    }
}

This SensitiveDataEnricher class implements the ILogEventEnricher interface, allowing it to inspect log events. If a log event contains the Password property, it replaces its value with a placeholder. To use this enricher, add it to the logger configuration:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .Enrich.With() // Add custom enricher
    .WriteTo.Console()
    .CreateLogger();

Edge Cases & Gotchas

While implementing secure logging practices, developers may encounter several pitfalls. One common mistake is to forget to exclude sensitive properties from log entries, leading to potential data exposure.

// Incorrect: Logging sensitive data
Log.Information("User logged in with password: {Password}", user.Password);

This example logs a user's password directly, which is a severe violation of secure logging practices. Instead, always ensure to redact or exclude sensitive data:

// Correct: Avoid logging sensitive data
Log.Information("User logged in");

Performance & Best Practices

When implementing secure logging, performance can be a concern, particularly in high-load applications. Here are some best practices:

  • Asynchronous logging: Use asynchronous logging to reduce the performance overhead of logging operations. Serilog supports asynchronous sinks that can help offload logging work to a separate thread.
  • Batching log entries: Configure batching to reduce the number of I/O operations, which can improve performance, especially in high-frequency logging scenarios.
  • Log levels: Use appropriate log levels to avoid logging excessive detail in production environments. This not only improves performance but also reduces the risk of sensitive data exposure.
  • Regular audits: Periodically review your logging configuration and practices to ensure compliance with security standards.

Real-World Scenario: Building a Secure Logging System

Let's create a mini-project that showcases secure logging in an ASP.NET Core web application. This application will include user authentication and log the activities without exposing sensitive information.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Serilog;

public class AccountController : Controller
{
    [HttpPost]
    public IActionResult Login(string username, string password)
    {
        // Simulating user authentication
        Log.Information("User {Username} is attempting to log in.", username);
        if (username == "admin" && password == "password")
        {
            Log.Information("User {Username} logged in successfully.", username);
            return Ok();
        }
        Log.Warning("User {Username} failed login attempt.", username);
        return Unauthorized();
    }
}

This AccountController class contains a Login action that logs the username when a user attempts to log in. It logs successful logins and failed attempts while ensuring that the password is never logged.

Conclusion

  • Understand CWE-532: Recognize the importance of avoiding sensitive data in logs to maintain security.
  • Utilize Serilog: Leverage Serilog's powerful features for structured and secure logging.
  • Implement filters and enrichers: Use filters to exclude sensitive data and enrichers to mask sensitive information dynamically.
  • Adopt best practices: Follow performance best practices to maintain application efficiency while logging securely.
  • Regularly review logging practices: Continuously audit and improve logging strategies to align with security standards.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

CWE-532: Secure Logging Practices to Prevent Sensitive Information Exposure
Mar 19, 2026
CWE-276: Fixing Insecure Default Configurations in ASP.NET Core Middleware Pipeline
Jun 09, 2026
CWE-829: Securing Third-Party Scripts and CDN Resources in ASP.NET Core with SRI
Jun 06, 2026
CWE-1236: Preventing CSV Injection in ASP.NET Core Excel and CSV Exports
Jun 05, 2026
Previous in ASP.NET Core
CWE-829: Securing Third-Party Scripts and CDN Resources in ASP.NE…
Next in ASP.NET Core
CWE-778: Implementing Security Audit Logging in ASP.NET Core with…
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    CWE-269: Improper Privilege Management - Implementing the … 361 views
  • 2
    Building Custom Bedrock Add-Ons with JavaScript: A Complet… 1,937 views
  • 3
    Send Email With HTML Template And PDF Using ASP.Net C# 17,201 views
  • 4
    Error-An error occurred while processing your request in .… 11,964 views
  • 5
    Elasticsearch Integration in ASP.NET Core - Full-Text Sear… 243 views
  • 6
    Fix Gemini API Error 429: Quota Exceeded on Free Tier (Sys… 827 views
  • 7
    Integrating Google reCAPTCHA v3 in ASP.NET Core for Seamle… 613 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26683 views
  • Exception Handling Asp.Net Core 21720 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 21177 views
  • How to implement Paypal in Asp.Net Core 20127 views
  • Task Scheduler in Asp.Net core 18201 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1780
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Products
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor