Why serilog not logging to file? - serilog

"WriteTo": [
{
"Name": "File"
},
{
"Name": "File",
"Args": {
"configureLogger": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/Error/applog.log",
"outputTemplate": "{Timestamp:o} [Thread:{ThreadId}] [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}
}
}
I have this in my app setting.json file?
Why serilog not writting to "path": "Logs/Error/applog.log", ?
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Logger.Information("Hello, world!");
I have this setting file ?
{
"Logging": {
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/Error/applog.log",
"outputTemplate": "{Timestamp:o} [Thread:{ThreadId}] [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
},
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"HrSoultion": "server=.;database=Maqta;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
}
}

Your configuration in appsettings.json doesn't seem to be correct.
If you provide this configuration, it should work:
{
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/Error/applog.log",
"outputTemplate": "{Timestamp:o} [Thread:{ThreadId}] [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}
}
My result:
For reference, I used .NET 6 and these NuGet packages:
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
Links:
https://github.com/serilog/serilog-sinks-file

Related

NET 5.0 - serilog-sinks-file not creating logs

Since I updated my code to .NET 5.0 and used a newer version of serilog, I cannot get any rolling file anymore
I tried debugging serilog , it creates a debug file but nothing is in there
private static void CreateLogger()
{
// Init Serilog configuration
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.logs.json")
.Build();
Log.Logger = new Serilog.LoggerConfiguration().ReadFrom.Configuration(configuration)
.Enrich.WithProperty("Application", GetAssemblyProductName())
.CreateLogger();
var file = File.CreateText(AppDomain.CurrentDomain.BaseDirectory + #"serilog.txt");
Serilog.Debugging.SelfLog.Enable(TextWriter.Synchronized(file));
Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
Serilog.Debugging.SelfLog.Enable(Console.Error);
}
here is my appsetings.log.json
{
"Serilog": {
"Using": [
"Serilog.Sinks.ApplicationInsights"
],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"System.Net.Http.HttpClient": "Warning"
}
},
"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": {
"pathFormat": "logs.txt",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
"outputTemplate": "({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"fileSizeLimitBytes": 50000000,
"rollOnFileSizeLimit": true,
"retainedFileCountLimit": 15,
"buffered": true
}
},
{
"Name": "ApplicationInsights",
"Args": {
"restrictedToMinimumLevel": "Information",
"outputTemplate": "({SourceContext}) ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}",
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
}
}
]
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "myapp"
}
}
}
am I missing something ?
thanks for helping me on this
Please someone correct me if this is wrong but I assumed you need to list the sinks you wanted to run in the Using section - therefore adding the File sink to your appsettings should fix this - as per below:
"Serilog": {
"Using": [
"Serilog.Sinks.ApplicationInsights","Serilog.Sinks.File"
],

Using RestrictedToMinimumLevel to Override the Default Minimum Level in Serilog

I have configured Serilog to have a default MinimumLevel of Verbose.
But I want to confine the logging to SQL Server to Warning (and up).
My config (in JSON) looks like this:
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.MSSqlServer", "My.Framework.AspNet" ],
"Enrich": [ "FromLogContext", "WithEventType" ],
"MinimumLevel": {
"Default": "Verbose"
},
"WriteTo": [
{
"Name": "MSSqlServer",
"restrictedToMinimumLevel": "Warning",
"Args": {
"connectionString": "Server=yada yada yada ;MultipleActiveResultSets=True",
"tableName": "ErrorLogs",
"autoCreateSqlTable": false,
"columnOptionsSection": {
"disableTriggers": true,
"clusteredColumnstoreIndex": false,
"primaryKeyColumnName": "Id",
"addStandardColumns": [ "LogEvent" ],
"removeStandardColumns": [ "Properties" ],
"additionalColumns": [
{
"ColumnName": "EventType",
"DataType": "bigint",
"AllowNull": true
}
],
"id": {
"columnName": "Id",
"nonClusteredIndex": true
},
"eventType": {
"columnName": "EventType"
},
"message": {
"columnName": "Message"
},
"messageTemplate": {
"columnName": "MessageTemplate"
},
"level": {
"columnName": "Level",
"storeAsEnum": false
},
"timeStamp": {
"columnName": "TimeStamp",
"convertToUtc": true
},
"exception": {
"columnName": "Exception"
},
"logEvent": {
"columnName": "LogEvent"
}
}
}
}
],
"Properties": {
"Application": "App API"
}
}
}
Upon inspecting my logs, I'm seeing everything from Verbose up.
Is there something I'm doing wrong with the restrictedToMinimumLevel property?
I also tried placing it inside the Args property, with no luck.
Cheers
I haven't tried it but upon this GitHub issue I think restrictedToMinimumLevel should be in Args. So change your WriteTo configuration like this:
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"restrictedToMinimumLevel": "Warning",
"connectionString": "Server=yada yada yada ;MultipleActiveResultSets=True",
"tableName": "ErrorLogs",
"autoCreateSqlTable": false,
"columnOptionsSection": {
"disableTriggers": true,
"clusteredColumnstoreIndex": false,
"primaryKeyColumnName": "Id",
"addStandardColumns": [ "LogEvent" ],
"removeStandardColumns": [ "Properties" ],
"additionalColumns": [
{
"ColumnName": "EventType",
"DataType": "bigint",
"AllowNull": true
}
],
"id": {
"columnName": "Id",
"nonClusteredIndex": true
},
"eventType": {
"columnName": "EventType"
},
"message": {
"columnName": "Message"
},
"messageTemplate": {
"columnName": "MessageTemplate"
},
"level": {
"columnName": "Level",
"storeAsEnum": false
},
"timeStamp": {
"columnName": "TimeStamp",
"convertToUtc": true
},
"exception": {
"columnName": "Exception"
},
"logEvent": {
"columnName": "LogEvent"
}
}
}
}
]
For the restrictedToMinimumLevel to work via configuration through appSettings.json, the restrictedToMinimumLevel must be inside the Args section as it's described in the documentation. There's nothing unique about the MsSQLServer sink that would require the configuration to be any different.
As you can see, only events with log level >= Warning are stored in the SQL Server table:
Program.cs
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Debugging;
namespace ReproSerilogSO66019586
{
class Program
{
static void Main(string[] args)
{
SelfLog.Enable(msg => Console.WriteLine("ERROR: {0}", msg));
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.WriteTo.Console()
.CreateLogger();
Log.Verbose("This is Verbose!");
Log.Debug("This is Debug!");
Log.Information("This is Information!");
Log.Warning("This is Warning!");
Log.Error("This is Error!");
Log.Fatal("This is Fatal!");
Log.CloseAndFlush();
Console.ReadLine();
}
}
}
appSettings.json
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.MSSqlServer" ],
"Enrich": [ "FromLogContext" ],
"MinimumLevel": {
"Default": "Verbose"
},
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"restrictedToMinimumLevel": "Warning",
"connectionString": "Server=(local);MultipleActiveResultSets=True",
"tableName": "ErrorLogs",
"autoCreateSqlTable": true,
"columnOptionsSection": {
"disableTriggers": true,
"clusteredColumnstoreIndex": false,
"primaryKeyColumnName": "Id",
"addStandardColumns": [ "LogEvent" ],
"removeStandardColumns": [ "Properties" ],
"additionalColumns": [
{
"ColumnName": "EventType",
"DataType": "bigint",
"AllowNull": true
}
],
"id": {
"columnName": "Id",
"nonClusteredIndex": true
},
"message": {
"columnName": "Message"
},
"messageTemplate": {
"columnName": "MessageTemplate"
},
"level": {
"columnName": "Level",
"storeAsEnum": false
},
"timeStamp": {
"columnName": "TimeStamp",
"convertToUtc": true
},
"exception": {
"columnName": "Exception"
},
"logEvent": {
"columnName": "LogEvent"
}
}
}
}
],
"Properties": {
"Application": "App API"
}
}
}

How many libraries can i have in the same angular workspace?

Can I have more than one library in the same angular workspace?
For Example:
lib-shared/
projects/
lib1
lib2
lib3
I tried to create a second library in my worskspace and import it into my app getting the following errors:
core.js:4442 ERROR TypeError: Cannot read property 'bindingStartIndex' of null
at ɵɵelementStart (core.js:14822)
at LsLibHeadToolbarComponent_Template (template.html:1)
at executeTemplate (core.js:7457)
at renderView (core.js:7264)
at renderComponent (core.js:8520)
at renderChildComponents (core.js:7138)
at renderView (core.js:7289)
at renderComponent (core.js:8520)
at renderChildComponents (core.js:7138)
at renderView (core.js:7289)
I noticed a strange thing: in the first library I created (working) in the src folder there are the files:
-public-api.ts
-test.ts
instead in the second library there are the files:
-projects.ts
-test.ts
this is my angular.json of workspace:
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ls-lib-menu": {
"projectType": "library",
"root": "projects/ls-lib-menu",
"sourceRoot": "projects/ls-lib-menu/src",
"prefix": "ls-lib-menu",
"architect": {
"build": {
"builder": "#angular-devkit/build-ng-packagr:build",
"options": {
"tsConfig": "projects/ls-lib-menu/tsconfig.lib.json",
"project": "projects/ls-lib-menu/ng-package.json"
},
"configurations": {
"production": {
"tsConfig": "projects/ls-lib-menu/tsconfig.lib.prod.json"
}
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "projects/ls-lib-menu/src/test.ts",
"tsConfig": "projects/ls-lib-menu/tsconfig.spec.json",
"karmaConfig": "projects/ls-lib-menu/karma.conf.js"
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"projects/ls-lib-menu/tsconfig.lib.json",
"projects/ls-lib-menu/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"ls-lib-head-toolbar": {
"projectType": "library",
"root": "projects/ls-lib-head-toolbar",
"sourceRoot": "projects/ls-lib-head-toolbar/src",
"prefix": "ls-lib-head-toolbar",
"architect": {
"build": {
"builder": "#angular-devkit/build-ng-packagr:build",
"options": {
"tsConfig": "projects/ls-lib-head-toolbar/tsconfig.lib.json",
"project": "projects/ls-lib-head-toolbar/ng-package.json"
},
"configurations": {
"production": {
"tsConfig": "projects/ls-lib-head-toolbar/tsconfig.lib.prod.json"
}
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "projects/ls-lib-head-toolbar/src/test.ts",
"tsConfig": "projects/ls-lib-head-toolbar/tsconfig.spec.json",
"karmaConfig": "projects/ls-lib-head-toolbar/karma.conf.js"
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"projects/ls-lib-head-toolbar/tsconfig.lib.json",
"projects/ls-lib-head-toolbar/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "ls-lib-menu",
"cli": {
"analytics": false
}
}
I imported both libraries into the app.module.ts file:
import { LsLibMenuModule } from '../../../../../ls-lib-shared/projects/ls-lib-menu/src/public-api';
import { LsLibHeadToolbarModule } from '../../../../../ls-lib-shared/projects/ls-lib-head-toolbar/src/projects';
Yes, you can have as many as you want. Just make sure you add them to the angular.json, but if you generate the library with the angular-CLI this will be done automatically.
https://angular.io/guide/creating-libraries

Build configuration failed in angular 7

I want deployed angular project on server , right now i am comment one server code and build the project. for example i build project for QA , and then comment , and next i build project for INT. this take lot time , and i have to repeat this step for my all server. for alternate i do following configuration
i add configuration added in angular.json , and run following command
ng build --configuration qa
it give me following error
Schema validation failed with the following
errors:
Data path "['build']" should NOT have additional properties(int).
following is my angular.json
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"newBuiildProcess": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/newBuiildProcess",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": [],
"es5BrowserSupport": true
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
},
"int": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.int.ts"
}
]
},
"qa": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.qa.ts"
}
]
},
"beta": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.beta.ts"
}
]
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "newBuiildProcess:build"
},
"configurations": {
"production": {
"browserTarget": "newBuiildProcess:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "newBuiildProcess:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.css"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"newBuiildProcess-e2e": {
"root": "e2e/",
"projectType": "application",
"prefix": "",
"architect": {
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "newBuiildProcess:serve"
},
"configurations": {
"production": {
"devServerTarget": "newBuiildProcess:serve:production"
}
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "newBuiildProcess"
}
anybody can help me on this??
From the look at your angular.json file, the error is pretty clear the property build should not have an int type, it simply doesn't work that way. Additional build types must be added under configurations property that is under the build property. You can read it like this. Build -> Configurations -> list of configurations(int, dev, bla bla, bla)
example:
"build": { "configurations":{ "prod": {// prodOptions}, "hmr": {// otherOptions} } }

Not able to import `.scss` file getting error

In angular I am getting following error:
ERROR in ./app/shared-components/header/header.component.scss
Module build failed (from ../node_modules/sass-loader/lib/loader.js):
#import '~styles.scss';
^
File to import not found or unreadable: ~styles.scss.
in D:\IBO\Project\IBO-UI\NG-IBO\src\app\shared-components\header\header.component.scss (line 4, column 1)
Error:
#import '~styles.scss';
here is my angular.json file:
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ibo": {
"root": "src",
"sourceRoot": "src",
"projectType": "application",
"prefix": "",
"schematics": {
"#schematics/angular:component": {
"styleext": "scss"
}
},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ibo",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src",
"src/assets",
"src/web.config"
],
"stylePreprocessorOptions": {
"includePaths": [
"node_modules/bootstrap",
"node_modules/angular-calendar",
"./src/styles"
]
},
"scripts": [
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
"styles": [
"node_modules/devextreme/dist/css/dx.common.css",
"node_modules/devextreme/dist/css/dx.light.css",
"node_modules/font-awesome/css/font-awesome.min.css",
"src/styles/styles.scss",
],
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "ibo:build"
},
"configurations": {
"production": {
"browserTarget": "ibo:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "ibo:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"./src/styles/styles.scss"
],
"scripts": [],
"assets": [
"./src/favicon.ico",
"./src/assets"
]
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"ibo-e2e": {
"root": "e2e/",
"projectType": "application",
"prefix": "app",
"architect": {
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "ibo:serve"
},
"configurations": {
"production": {
"devServerTarget": "ibo:serve:production"
}
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "ibo"
}
How to come up with this?
Thanks in advance.
// Angular CLI: 7.3.9
// Node: 10.15.0
// OS: win32 x64
// Angular: 7.2.15
Hi,
Here is how I fixed my problem.
I created file with variables in
src/theme/_project-variables.scss
then inside main.scss and component.scss files i used
#import "~theme/project-variables";
If you don't put "_" in filename it will not render.
Also you need to include this file in every component.scss's where you want to use your variables.

Resources