Spa.Cbcrc.Logging 1.1.2

There is a newer version of this package available.
See the version list below for details.
The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package Spa.Cbcrc.Logging --version 1.1.2
NuGet\Install-Package Spa.Cbcrc.Logging -Version 1.1.2
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Spa.Cbcrc.Logging" Version="1.1.2" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Spa.Cbcrc.Logging --version 1.1.2
#r "nuget: Spa.Cbcrc.Logging, 1.1.2"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Spa.Cbcrc.Logging as a Cake Addin
#addin nuget:?package=Spa.Cbcrc.Logging&version=1.1.2

// Install Spa.Cbcrc.Logging as a Cake Tool
#tool nuget:?package=Spa.Cbcrc.Logging&version=1.1.2

Spa.Cbcrc.Logging

Spa.Cbcrc.Logging is the official package of the Software and Platform Architecture team's logging solution for Merlin Template driven applications. The package leverages the Serilog library and supports logging to Files as well as to Azure Log Analytics.

Table of Contents

Installation

Chose one of the following way to install the package:

  • Use Visual Studio's Package Manager Console and search for Spa.Cbcrc.Logging

  • Navigate to your project's directory and use the following command:

dotnet add package Spa.Cbcrc.Logging

The package needs to be added to every project that requires it.

Usage

Spa.Cbcrc.Logging leverages Dependency Injection to provide the logging methods to your own controllers or services. The service needs to be registered in the Program.cs of all of your relevant projects in order to be injected in the constructor or your classes.

The Spa.Cbcrc.Logging CbcrcLogger class can also be instantiated by passing the configuration settings as constructor parameters for use cases where Dependency Injection would be impractical, for example, for Console Application like Windows Services.

In order to configure Spa.Cbcrc.Logging correctly, the proper configuration has to be entered in the project's appSettings.json, App.Config or Web.Config file.

Configuration

appSettings.json
{   
    "ApplicationId": "[Application Name]",
    "Serilog": {
    "MinimumLevel": {
      "Default": "Warning",
      "Override": {
        "Microsoft": "Error",
        "System": "Error"
      }
    },
    "FileSink": {
      "OutputTemplate": "{Timestamp} [{Level}] V{Release} (#{ProcessId}-{ThreadId}) {Message}{NewLine}{Exception}",
      "Path": "c:\\Logs\\[Application Name]\\log-api-.txt",
      "RollingInterval": "Day",
      "RetainedFileCountLimit": 14,
      "MinimumLevel": "Information"
    },
    "AzureLogAnalytics": {
      "MinimumLevel": "Information",
      "WorkspaceId": "d953bda0-1a70-4c32-a98e-9434bd6d8b78",
      "PrimaryKey": "@---ReplaceInCICD-AzureLogAnalyticsKey---@"
    }
  },
}
App.config or Web.config
<add key="ApplicationId" value="[Application Name]" />
<add key="Serilog:MinimumLevel:Default" value="Information" />
<add key="Serilog:MinimumLevel:Override:Microsoft" value="Error" />
<add key="Serilog:MinimumLevel:Override:Error" value="Error" />
<add key="Serilog:FileSink:OutputTemplate" value="{Timestamp} [{Level}] V{Release} (#{ProcessId}-{ThreadId}) {Message}{NewLine}{Exception}" />
<add key="Serilog:FileSink:Path" value="c:\\Logs\\[Application Name]\\log-api-.txt" />
<add key="Serilog:FileSink:RollingInterval" value="Day" />
<add key="Serilog:FileSink:RetainedFileCountLimit" value="14" />
<add key="Serilog:FileSink:MinimumLevel" value="Information" />
<add key="Serilog:AzureLogAnalytics:MinimumLevel" value="Information" />
<add key="Serilog:AzureLogAnalytics:WorkspaceId" value="d953bda0-1a70-4c32-a98e-9434bd6d8b78" />
<add key="Serilog:AzureLogAnalytics:PrimaryKey" value="@---ReplaceInCICD-AzureLogAnalyticsKey---@" />
Configuration Parameters
Property Description Required
ApplicationId Short name of the application that will appear in Azure Log Analytics (the name will be transformed automatically into PascaleCase). Ex.: merlin-template
Serilog.MinimumLevel.Default The minimum logging level for all logging methods (File Sink and Azure Log Analytics). This setting will override the finer grained minimum levels. Allowed values: Debug, Verbose, Fatal, Error, Warning, Information.
Serilog.MinimumLevel.Override Overrides the .Net namespace minimum logging levels. Allowed values: Debug, Verbose, Fatal, Error, Warning, Information.
Serilog.FileSink.OutputTemplate For File Sink logging: The format of the log events.
Serilog.FileSink.Path For File Sink logging: The path where the log file will be saved.
Serilog.FileSink.RollingInterval For File Sink logging: The frequency at which the log file is overwritten with new logs. Allowed values: Minute, Hour, Day, Month, Year, Infinite.
Serilog.FileSink.RetainedFileCountLimit For File Sink logging: The number of files that can be generated inside the rolling interval.
Serilog.FileSink.MinimumLevel For File Sink logging: The minimum logging level. Allowed values: Debug, Verbose, Fatal, Error, Warning, Information.
Serilog.AzureLogAnalytics Section for Azure Log Analytics settings. The section is not mandatory and can be left missing for local development. If you wish to to log to Azure Log Analytics in local development, please do not commit secrets to your repository. For Local development: you can use the .Net Secret Manager
Serilog.AzureLogAnalytics.MinimumLevel For Azure Log Analytics logging: The minimum logging level. Allowed values: Debug, Verbose, Fatal, Error, Warning, Information.
Serilog.AzureLogAnalytics.WorkspaceId For Azure Log Analytics logging: The Azure Log Analytics GUID: <br/> Business <br/> Nonprod: c664d046-45fb-4a81-9f15-639338e15607 <br/> Prod: c0336ed8-467b-44f9-8c3d-27ba144cc822 <br/> Content <br/> Nonprod: 47cb679d-fb74-446d-b757-fd4e22ec7f5a <br/> Prod: d9e1180c-c2a2-4d65-84ae-935097f29d50 <br/> Media <br/> Nonprod: 0d03b14e-9f7e-4115-b8be-a9c62e8b3d67 <br/> Prod: 0d201065-173c-4ff0-911f-1bf9e9d8d886
Serilog.AzureLogAnalytics.PrimaryKey For Azure Log Analytics logging: The transformation string for the Azure Log Analytics secret Primary Key. Set it to: "@---ReplaceInCICD-AzureLogAnalyticsKey---@"

Spa.Cbcrc.Logging classes and interfaces

  • Spa.Cbcrc.Logging.ICbcrcLogger <br/> Interface used to define the type of the injected Logging service.

  • Spa.Cbcrc.Logging.Settings <br/> This class defines the AppSetting properties and is used to construct an Options pattern settings class for your project. Needs to be used to bind to IConfigurationBuilder in the case of console application.

Registering the Spa.Cbcrc.Logging Service for dependency injection

.Net 6 and .Net Core

For projects that use WebApplicationBuilder, like Web APIs and Web Applications, simply register the service in the Program.cs class (or Startup.cs for .Net Core). Note that it is also possible to use dependency injection for Console Applications (Windows Services): https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-usage

Program.cs

builder.Services.AddCbcrcLogger();
.Net 4.8

For Full Framework projects, you may use a dependency injection library like Ninject, Simple Injector or Autofac to register and inject the Logging service. Please note that you will have to provide the NameValueCollection object from ConfigurationManager to the CbcrcLogger class constructor.

Registering the Logging service with Ninject

private static void RegisterServices(IKernel kernel)
{
  // The ConfigurationManager.AppSettings property provides a NameValueCollection object
  var appSettings = ConfigurationManager.AppSettings;
  kernel.Bind<ICbcrcLogger>().ToConstructor(arg => new CbcrcLogger(appSettings));
}   

Instantiating the CbcrcLogger class

For certain Console Application projects, like Windows Services, where dependency injection may prove impractical, you can instantiate a CbcrcLogger class in order to pass it down child classes as a parameter. A configuration settings object will need to be passed to the class constructor.

.Net 6 and .Net Core

In this case, a IConfigurationRoot object must be instantiated. Then, using this object, instantiate the CbcrcLogger class in the Program.cs class (or Startup.cs for .Net Core).

Program.cs

// Instantiate appSettings object for configuration
IConfigurationRoot configuration = new ConfigurationBuilder().Build()

//Configure Serilog
_logger = new CbcrcLogger(configuration);
.Net 4.8

For .Net 4.8 projects, a NameValueCollection object must be instantiated from the ConfigurationManager class. Then, using this object, instantiate the CbcrcLogger class in the Program.cs class (or Startup.cs for .Net Core).

Startup.cs

// The ConfigurationManager.AppSettings property provides a NameValueCollection object
NameValueCollection appSettings = ConfigurationManager.AppSettings;

_cbcrcLogger = new CbcrcLogger(appSettings);

Registering the service as ILogger

If you need to register the Logging service as a custom ILogger provider, use the following instructions.

.Net 6

In the Program.cs class, the UseCbcrcLogger() extension can be used with the host builder.

Program.cs

var builder = WebApplication.CreateBuilder(args);
IConfigurationRoot configuration = new ConfigurationBuilder().Build()
builder.Host.UseCbcrcLogger(configuration);
var app = builder.Build();
.Net Core

In the Program.cs class, the UseCbcrcLogger() extension can be used with the host builder.

Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                        .AddEnvironmentVariables()
                        .Build();
            var host = BuildWebHost(args, config);
            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args, IConfigurationRoot config) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseCbcrcLogger(config)
                .Build();
    }
.Net 4.8

In the Startup.cs class, use the UseCbcrcLogger() static method with the LoggerFactory() class.

Startup.cs

var loggerFactory = new LoggerFactory();
var appSettings = ConfigurationManager.AppSettings;
Registration.UseCbcrcLogger(loggerFactory,appSettings);

var logger = loggerFactory.CreateLogger<Startup>();

Using the Logging Service

Simply declare an ICbcrcLogger variable in your class and assign the injected services from the class constructor to the variable like so:

public class MyController : ApiBaseController
{
    private readonly ICbcrcLogger _logger;

    public MyController(ICbcrcLogger logger)
    {
        _logger = logger;
    }
}

Please note that for Console Application like Windows services, the Logging service can be passed as a parameter to the different classes that require it.

_logger = new CbcrcLogger(configuration);

new Worker(serviceInterval, serviceName, _logger);

The ICbcrcLogger service can then be used with it's different methods that refer to all of the available logging levels. For example:

try
{
  // Your code here...
}
catch(Exception ex)
{
    _logger.Error("MyController", ex);
}

Here are the available logging methods. Note that the non mandatory "assemblyName" parameter is used to enable or disable concatenating the project name to the Scope property of the log events. Ex: [Service], [Api]

public interface ICbcrcLogger
{
    void Debug(string scope, string msg, string email = "", bool assemblyName = true);

    void Verbose(string scope, string msg, string email = "", bool assemblyName = true);

    void Info(string scope, string msg, string email = "", bool assemblyName = true);

    void Warning(string scope, string msg, string email = "", bool assemblyName = true);

    void Error(string scope, Exception ex, string email = "", bool assemblyName = true);

    void Fatal(string subFilter, Exception ex, string email = "", bool assemblyName = true);
}

Sample Code

The Merlin Template repository integrates the Spa.Cbcrc.Logging package. <br/> it-apps-merlin-template

Contributing

Pull requests are welcome. For major changes, please contact the SPA team to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
8.0.1 158 12/21/2023
6.0.4 93 12/21/2023
1.4.1 142 11/16/2023