-
Notifications
You must be signed in to change notification settings - Fork 147
ConnectionString not being read from ConnectionStrings section #150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Please post your config file and your init code. Also please post the versions you're using. Are you configuring the sink directly or via If you're configuring it directly, it probably isn't clear from the docs (we're having a discussion now about improving Serilog docs in general), but to use a named connection string, you must use the The only other two requirements that come to mind is that the connection string section must be named We actually have a passing test for this: |
Using the dev version of the SQL sink and the 3.0.0 release of the config package, this code and config works: var appConfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json")
.Build();
var logConfig = new LoggerConfiguration();
logConfig.ReadFrom.Configuration(appConfig);
Log.Logger = logConfig.CreateLogger();
Serilog.Debugging.SelfLog.Enable(Console.Error);
Log.Information("An Information message");
Log.CloseAndFlush(); {
"ConnectionStrings": {
"DevTest": "Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=SerilogTest;Integrated Security=true"
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "DevTest",
"tableName": "Issue81",
"autoCreateSqlTable": true,
"columnOptionsSection": {
"customColumns": [
{
"ColumnName": "EventType",
"DataType": "int"
},
{
"ColumnName": "Release",
"DataType": "varchar",
"DataLength": 32
}
]
}
}
}
]
}
} |
@MV10 When is it expected to be released the final 5.1.3 version of |
@OculiViridi not my call, but once I'm done with this change I'm going to talk to Nick about doing a release. Cumulative dev changes are big enough to justify a bump to 5.2 ... I even think 6.0 could be warranted, but I don't work with .NET Framework any more (increasingly pointless) and that side has been neglected. I started working in this sink specifically because I needed it for Core but it didn't support modern config sources. But maybe I'll bite the bullet and bring that up to snuff, too. |
@craigmoliver I also set up the test with a bogus connection string, and this is what hits the console via SelfLog upon auto-create and then after a message is logged:
|
Hello, I'm facing the same issue as @craigmoliver. public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);
});
}
public class Startup
{
private readonly ILoggerFactory _loggerFactory;
public Startup(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
_loggerFactory.AddSerilog();
Serilog.Debugging.SelfLog.Enable(Console.Error);
app.Run(async (context) =>
{
var logger = _loggerFactory.CreateLogger<Startup>();
logger.LogInformation("Information message");
await context.Response.WriteAsync("Hello World!");
});
}
} {
"ConnectionStrings": {
"DevTest": "Data Source=.\\sqlexpress;Database=SerilogTest;Integrated Security=true"
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "DevTest",
"tableName": "Issue81",
"autoCreateSqlTable": true,
"columnOptionsSection": {
"customColumns": [
{
"ColumnName": "EventType",
"DataType": "int"
},
{
"ColumnName": "Release",
"DataType": "varchar",
"DataLength": 32
}
]
}
}
}
]
}
} If I replace "DevTest" with the actual connection string, it works, otherwise i get
Only packages i have installed : <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.4" />
<PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.1.2" />
</ItemGroup> |
@nlz242 Did you tried using the dev package of Serilog.Sinks.MSSqlServer v5.1.3? |
@OculiViridi I did and it crashes (NullReferenceException) on .UseSerilog((hostingContext, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);
}); Stacktrace :
This happens with 5.1.3 prerelease 00231 & 00229. |
@nlz242 Like you said previously:
Are you still using this? "Args": {
"connectionString": "DevTest", I'm currently running without problems Serilog on Console and SQL Server 2016, using the following packages:
Maybe these links can also be useful. Please try to take a look: |
Yes still using "DevTest" as the connection string, with a connection string named DevTest defined in the connectionstrings section. I debugged a bit just to see if i could figure it out. It seems that the static ConfigurationManager just doesn't find the connection string. |
Upon further investigation, it seems like this is a Nuget "issue". Nuget pickups the net45 assembly instead of the netstandard2.0 one, since the project is .NET Framework. I'll try choosing my DLL manually and report back with my findings. Related to NuGet/Home#7385 |
Referencing the netstandard dll directly, instead of the nuget packages, i was able to get the proper LoggerConfigurationMSSqlServerExtensions to run, however i was never able to actually get IConfiguration injection to work, even when creating the logger by hand: private static IConfiguration Configuration { get; set; }
public static void Main(string[] args)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddCommandLine(args)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables().Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
CreateWebHostBuilder(args).Build().Run();
} I always end up with a null IConfiguration so obviously, getting the connection string fails and returns a null. I guess i'm gonna stick with providing the connection string directly in MSSqlServer's Args instead of trying to get Named connection string to work. I've included my repro project. I'd also like to mention that after my tests, i am VERY worried about the upcomming version. Current version (5.1.2) works properly with ASP.NET Core projects targetting Full frameworks, except for named connecting strings, however 5.1.3 previews stop working completly. You can use my repro to see it for yourself, just upgrading 5.1.2 to 5.1.3-dev-00231 breaks the application, Creating the logger is no longer possible. |
Good news is, using @MV10 issue_161 branch, named connection string still don't work but at least ASPNET Core with Full Framework (4.7) works as expected. Less worried now. |
Hi, I just hit this issue moving the sink configuration to the ASP.NET Core 2.1 project targeting .NET Core here ( Any chance to have a fix soon? Thanks in advance. |
@craigmoliver |
Edit: with further testing, I cannot get any version higher than Serilog.Settings.Configuration v3.0.0 to 3.0.1-dev-00160 work properly. I have had some success using name connection strings with the following: Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(GetFileConfiguration())
.CreateLogger(); Note, I am manually loading private static IConfigurationRoot GetFileConfiguration()
{
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: false)
.AddEnvironmentVariables()
.Build();
} Package References <PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1-dev-00160" />
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.1.3-dev-00232" /> |
Does that mean lesser version of Serilog.Settings.Configuration 3.0.1-dev-00160 work? What's the difference between them? |
I was having the same problem, but @EEParker's workaround does the job on an asp.net core 2.1 project |
I got it working with these versions:
It also works with these versions:
Interestingly these versions DO NOT work. Strange how the release version fails.
|
I can confirm @craigmoliver findings.
I can also add that the following combination does NOT work :
|
I'm also having issues. I'm hosting in Azure and using the Azure AppSettings and when I try to run the website I get a null exception on the connection string. If I hard code the connection string in the appsettings.json it works fine, but if I reference a connection string it doesn't work. "Application startup exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentNullException: Value cannot be null. Parameter name: connectionString at Serilog.Sinks.MSSqlServe r.MSSqlServerSinkTraits..ctor(String connectionString, String tableName, String schemaName, ColumnOptions columnOptions, IFormatProvider formatProvider, Boolean autoCreateSqlTable) at Serilog.LoggerConfigurationMSSqlServerExtensions.MSSqlServer(LoggerSinkConfiguration loggerConfiguration, String connectionString, String tableName, IConfiguration appConfiguration, LogEventLevel restrictedToMinimumLevel, Int32 batchPostingLimit, Nullable`1 period, IFormatProvider formatProvider, Boolean autoCreateSqlTable, ColumnOptions columnOptions, IConfigurationSection columnOptionsSection, String schemaName) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Serilog.Settings.Configuration.ConfigurationReader.CallConfigurationMethods(ILookup at Serilog.Settings.Configuration.ConfigurationReader.ApplySinks(LoggerConfiguration loggerConfiguration, IReadOnlyDictionary`2 declaredLevelSwitches) at Serilog.Settings.Configuration.ConfigurationReader.Configure(LoggerConfiguration loggerConfiguration) at Serilog.Configuration.LoggerSettingsConfiguration.Settings(ILoggerSettings settings) at Serilog.ConfigurationLoggerConfigurationExtensions.Configuration(LoggerSettingsConfiguration settingConfiguration, IConfiguration configuration, DependencyContext dependencyContext) at StartupHelpers.AddLogging(IApplicationBuilder app, ILoggerFactory loggerFactory, IConfiguration configuration) in IdentityServer4.STS.Identity\Helpers\StartupHelpers.cs:line 118 at Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) in IdentityServer4.STS.Identity\Startup.cs:line 45 --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app) at Microsoft.AspNetCore.Mvc.Internal.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder) at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app) at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()" |
From almost one year till now this issue still open! O_O |
still open??? Time to change to something else.... |
Haven't tried in ASP.NET Core Targetting full framework (472 or 48) lately, but ASP.NET Core on .NET Core works as expected. Versions tested : So this seems all good to me. Maybe someone else can chime in and say if they are still encountering this issue. |
I verified it too with the current version Serilog.Sinks.MSSqlServer 5.5.0 and Serilog.Settings.Configuration version 3.1.0. I used the sample program in Closing this issue now. |
Hi, does Serilog.Sinks.MSSqlServer have the feauture with named connection strings? What was the final word on this. |
Hi @MrBjorn, Judging from my last comment above (which is some years back so I cannot remember details :)) it is supported and works as expected. |
Thanks @ckadluba ! :-) I verified it in latest version and in .NET8. Can simplify the json's a bit. |
I do not want to duplicate my connection string so I attempted to do the following per your documentation:
"To use a connection string from the connectionStrings section of your application config, specify its name as the value of the connection string."
This does not work when setting configuration in the appSettings.json using the serilog/serilog-settings-configuration package. Only actual connection strings work, not the name of the settings from the ConnectionStrings section.
The text was updated successfully, but these errors were encountered: