Static class with unique id per request
I want to achieve something similar (but much simpler) like Serilog sinks without using DI explicitly.
It's easy to do with DI you just have to register service as scoped and just create id when object is initialized.
But how to achive that with static class? It's somehow possible because .Net Serilog team did that.
If you want to use their logger you should simple inicialize it:
Log.Logger = new LoggerConfiguration()
.Filter.ByExcluding(c => c.Properties.Any(p => p.Value.ToString().Contains("swagger")))
.Filter.ByExcluding(c => c.Properties.Any(p => p.Value.ToString().Contains("liveness")))
.Enrich.FromLogContext()
.WriteTo.Console(new ElasticLogFormatter())
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticConfiguration.Url))
{
AutoRegisterTemplate = true,
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
IndexFormat = elasticConfiguration.Index,
CustomFormatter = new ElasticLogFormatter()
})
.CreateLogger();
And whenever you use:
Log.Information("message");
It contains unique request id within single request despite where you use this (controller, service, db context - they all shere the same id).
I've found their code on github but with that it still remains a struggle to find where and how they achived that. https://github.com/serilog/serilog
do you know?
how many words do you know
See also questions close to this topic
-
site only opens in CefSharp
zaakr.net is a site can be opened only in zaakr.exe application or through android(.apk), when opened in browser u been redirected to https://browser.zaakr.net so u download there application, (.exe) file is using cefsharp as a browser so it can access website, from 2 month i could open it from chromium as cefsharp uses chromium, now i can't access website through chromium for some reason idk, i even made a cefsharp browser myself using visual studio nothing worked all the time i been redirected to browser.zaakr.com, i want to access through any browser that have devtools available for a project, note that application zaakr.exe is still using cefsharp even the older version still can access site. i would appreciate any help, sry for any spelling mistakes, thanks.
-
C# MariaDB Update Function working in DataStore but not updating in .NET Application
My initial issue is that my database does not update when I call on this specific code. I am not sure if it is C# itself or the update query that I am calling.
string _connectionString = "validConnectionstring"; using (MySqlConnection _mySqlConnection = new MySqlConnection(_connectionString) { _mySqlConnection.Open(); using (MySqlCommand command = new MySqlCommand("UpdateProfileStatus", _mySqlConnection)) { command.Transaction = _mySqlConnection.BeginTransaction(); command.CommandTimeout = TimeSpan.FromSeconds(60).Seconds; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@_username", "test"); command.Parameters.AddWithValue("@_status", true); command.ExecuteNonQuery(); } _mySqlConnection.Close(); }
I get no updates in my database but my console logs that the query is executed returning the value of 1 but there is no update that actually happens in my DB. Is there something in my code to reason why it is failing?
Here is the stored procedure that I have for the update command
CREATE PROCEDURE UpdateProfileStatus(_username VARCHAR(25), _status BOOL) UPDATE Profile SET status = _status WHERE username = _username;
I know the Stored Procedure works but am not sure why my .NET application is not responding to my procedure call. Is it something to do with my implementation of the parameters or is it my procedure itself?
-
How to add a new Model visually in Mac OS visual Studio
I do not see any choice to create a model in Mac visual studio? I In the windows version the Class created with its imports
using Linq
using Threading.Tasks
using Collection.Generic
-
How to access variable from a function in a required file that required another file? Can I do it directly, without using $GLOBALS?
So I have the following 3 files:
index.php
<?php require("require/functions.php"); $g = getGroup(); var_dump($data); die(); ?>
functions.php
<?php function getGroup(){ if(condition) $g = 1; else if(another condition) $g = 2; else if...etc require("data/$g.php"); return $g; } ?>
An example e.g. data/1.php file:
<?php $data = ["Some random data"]; ?>
I tried various approaches like using
global $data
inindex.php
and various other things, but didn't have any luck using this approachI could do it by changing the
getGroup()
function togetGroupAndData()
and returning[$g, $data]
, however that isn't really ideal...Likewise I also created a global variable
$temp
infunctions.php
, used$temp = $data
, then could useglobal $temp
in theindex.php
fileMy current preferred method is just to use
$GLOBALS['data'] = $data
inside thegetGroup()
, function, though I'm curious, is there anyway I can access this$data
array from within theindex.php
file without having to use these workarounds?Thanks
-
Mocking scope function in Kotlin
I am using following object creation methods in kotlin
class Resource( referenceFactory: ReferenceFactory, id: String, name: String, role: String, odi_runs: int, odi_wickets: int, test_runs: int, test_wickets: int){ referenceFactory.calculateRank(Player().apply { id = id name = name role = role odi_runs = odi_runs odi_wicket = odi_wickets test_runs = test_runs test_wicket = test_wicket }) }
then I use this created object for calculate the rank of the player. To get the valid test result from reference factory, I need to mock this 'Player' object creating scope method.
-
Svelte reactive statement with a variable fron onMount
I'm trying to style the currently active tab of my web project with the class "active". To target my tab elements I am using
onMount(() => { const links = document.querySelectorAll(".topnav a"); });
I am then using a reactive statement to style the appropriate element like this
$: { links.forEach((link) => { if (link.getAttribute("id") === $page.url.pathname) { link.classList.add("active"); } else { link.classList.remove("active"); } }); }
However, I have no way of sharing the
links
variable to my reactive statement. I also tried puttingdocument.querySelectorAll
inside my reactive statement (not using onMount at all), which worked flawlessly until i reloaded the page. What is the conventional approach to this? -
AppInsights telemetry not co-existing with SeriLog logging
my Program.cs is configured like this
using Infrastructure; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.AzureAD.UI; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.Identity.Web; using Microsoft.Identity.Web.TokenCacheProviders.InMemory; using Serilog; using Serilog.Events; using Services; using Services.Contracts; var MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; var builder = WebApplication.CreateBuilder(args); //builder.Services.AddApplicationInsightsTelemetry(opt => opt.EnableActiveTelemetryConfigurationSetup = true); var logger = new LoggerConfiguration() // .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) // Filter out ASP.NET Core infrastructre logs that are Information and below .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .ReadFrom.Configuration(builder.Configuration) .Enrich.FromLogContext() .CreateLogger(); try { // clear all exsiting logging proveriders builder.Logging.ClearProviders(); builder.Logging.AddSerilog(logger); builder.Services.AddApplicationInsightsTelemetry(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); //builder.Services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme) // .AddAzureADBearer(options => configuration.Bind("AzureAd", options)); builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration, "AzureAd"); builder.Services.AddCors((options => { options.AddPolicy(MyAllowSpecificOrigins, builder => builder .WithOrigins("http://localhost:4200", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() ); })); var connectionString = configuration.GetConnectionString("BBBankDBConnString"); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddScoped<ITransactionService, TransactionService>(); builder.Services.AddScoped<DbContext, BBBankContext>(); builder.Services.AddDbContext<BBBankContext>( b => b.UseSqlServer(connectionString) .UseLazyLoadingProxies(true) ); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseCors(MyAllowSpecificOrigins); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run(); } catch (Exception ex) { logger.Fatal(ex, "Error Starting BBBank API"); } finally { logger.Dispose(); }
and the settings are like this
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "BBBankDBConnString": "Server=tcp:xxxx.database.windows.net,1433;Initial Catalog=BBBankDB;Persist Security Info=False;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" }, "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "bbbankAD.onmicrosoft.com", "TenantId": "0c087d99-9bb7-41d4-bd58-80846660b536", "ClientId": "api://bbbankapi", "Audience": "api://bbbankapi" }, // To configure app insight custom events (custom events for User Specific Actions (User Accessed Accounts Data)) "ApplicationInsights": { "InstrumentationKey": "xxx-ecc6-43d0-9fab-a0d996f4cf07", "EnableAdaptiveSampling": false, "EnablePerformanceCounterCollectionModule": false }, // To Configure App Insights logging (Applucation Specific Logs e.g Controller Hit) "Serilog": { "Using": [ "Serilog.Sinks.ApplicationInsights", "Serilog.Sinks.File" ], // "Serilog.Sinks.Debug", "Serilog.Sinks.File", "MinimumLevel": "Information", // Where do we want to write our logs to? Choose from a large number of sinks: // https://github.com/serilog/serilog/wiki/Provided-Sinks. "WriteTo": [ //{ // "Name": "Debug" //}, { "Name": "File", "Args": { "path": "Logs/log.txt" } }, { "Name": "ApplicationInsights", "Args": { "instrumentationKey": "xxx-ecc6-43d0-9fab-a0d996f4cf07", //"restrictedToMinimumLevel": "Information", "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights" } } ], "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], "Properties": { "Application": "Sample" } } }
and the packages i have are these ones
<ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="6.0.4" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.3"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="6.0.3" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.3" /> <PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.23.1" /> <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.20.0" /> <PackageReference Include="Serilog.AspNetCore" Version="5.0.0" /> <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" /> <!--<PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" /> <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" /> <PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />-->
Problem: but the telemetry is working but logging is not working . I have tried different combinations of packages as well. Also tried commenting out one over the other but results are stil the same.
using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Mvc; namespace BBBankAPI.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; private readonly TelemetryClient telemetryClient; public WeatherForecastController(ILogger<WeatherForecastController> logger, TelemetryClient telemetryClient) { _logger = logger; this.telemetryClient = telemetryClient; } [HttpGet] public IEnumerable<WeatherForecast> Get() { _logger.LogInformation("This is not showing in Azure portal but showing in file"); telemetryClient.TrackTrace("This is showing in Azure Portal"); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } }
-
Serilog with Graylog not logging
I have a Web API and I'm trying to log messages into Graylog, using Serilog. Now matter what I do, no messages are shown in my Graylog application. This is what I have so far:
This is in my Program.cs
var logger = new LoggerConfiguration(). ReadFrom.Configuration(builder.Configuration). Enrich.FromLogContext(). CreateLogger(); builder.Logging.ClearProviders(); builder.Logging.AddSerilog(logger);
This is my configuration:
"Serilog": { "Using": [ "Serilog.Sinks.Graylog" ], "MinimumLevel": "Information", "WriteTo": [ { "Name": "Graylog", "Args": { "hostnameOrAddress": "127.0.0.1", "port": "12201", "transportType": "Udp" } } ], "Properties": { "Application": "Centralized logging application" } }, "AllowedHosts": "*" }
And I'm trying to log a:
_logger.LogError(0, new Exception("Exception Message"), "Message", new WeatherForecast());
Can someone please help me? I need to see my exception inside Graylog.
Thanx a lot in advance
-
Amazon S3 sink in serilog is not working. How to use s3 Sink with serilog?
public class program { public static void Main(String args[]) { var levelSwitch = new LoggingLevelSwitch(); levelSwitch.MinimumLevel = LogEventLevel.Information; try { var logger = new LoggerConfiguration().WriteTo .AmazonS3( "log.txt", "xxxxxxx", //bucketName Amazon.RegionEndpoint.EUWest1, "xxxx", //accessKey "xxxx", //secretKey restrictedToMinimumLevel: LogEventLevel.Information, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", new CultureInfo("de-DE"), levelSwitch: levelSwitch, rollingInterval: RollingInterval.Minute, encoding: Encoding.Unicode ) .CreateLogger(); logger.Debug("Hello world Debug mode on"); logger.Information("Hello world Debug mode on"); logger.Error("Hello world Debug mode on"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } }
and if I remove output template and culture then I face the ambiguity error. How can I use this amazon s3 sink correctly ?. and I am not getting any error in the catch block and nothing happen in the s3 bucket there was no file is making