I am trying to do a little spike and I cannot get log file generated.
This is my NLog configuration:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.2.4.0" newVersion="3.2.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<nlog throwExceptions="true"
internalLogLevel="Warning"
internalLogFile="Rebus.Tests.Output.NLog.Internal.log"
internalLogToConsole="true"
xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="normalLogfile" type="File" fileName="${basedir}/Rebus.Tests.Output.log" />
<target name="normalConsole" type="Console" detectConsoleAvailable="true" />
</targets>
<rules>
<logger name="NormalLog" minlevel="Trace" writeTo="normalLogfile, normalConsole" />
</rules>
</nlog>
</configuration>
And here is my static Main in the Console Application:
var logger = LogManager.GetLogger("NormalLog");
logger.Error("This is a log error line");
But nothing is logged neither LogFile nor Console.
The application.exe.config is in the bin/Debug runtime folder.
And I am looking for the log file with SearchEverything so it will found in any folder where it is.
Adding some information to this question if I put a breakpoint to inspect logger variable I can see no configuration was read:
Try to change
var logger = LogManager.GetLogger("NormalLog");
to
var logger = LogManager.GetLogger("normalLogfile");
because as far as I know you have to get the logger via target-name and not via rule-name.
//edit
Have you tried to remove the nlog attributes in you app.config? Just to be sure none of them is the problem.
Related
I am absolutely at my wits end with this, having tried basically everything. I also do not see any existing stackoverflow threads about doing this.
I have an app.config file for my C# project, and it stores a list of servers which the user can create and add to.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="servers" type="System.Configuration.AppSettingsSection" />
</configSections>
<servers>
<add key="server" value="678,true,true"/>
</servers>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
</startup>
<appSettings>
<add key="nightmode" value="Dark"/>
<add key="theme" value="Red"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="ControlzEx" publicKeyToken="69f1c32f803d307e" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
((NameValueCollection)ConfigurationManager.GetSection("servers")).Add("server", $"{port}," + $"{ (dialogResult1 == MessageDialogResult.Affirmative) },{dialogResult2 == MessageDialogResult.Affirmative}");
When the user goes to add a new key the the "servers" section, it throws the below exception.
System.Configuration.ConfigurationErrorsException: 'The configuration is read only.'
I am bewildered why this is happening
you can try:
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("test", "propertyValue");
config.Save(ConfigurationSaveMode.Modified, true);
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
string test = ConfigurationManager.AppSettings["test"];
This get de appsettings section values.
Ps.: You need Install-Package System.Configuration.ConfigurationManager.
I ended up generating my own XML configuration, since that appears to be the best way to do things.
I have created a console app in c# that reads information from App.config. if i add things in appSettings section, i can acces them and it works, but as soon as i add some custom sections i cant read anything from it. I am using ConfigurationManager, and i have the reference for it included.
My app config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
and i am trying to acces those information like this:
string path = ConfigurationManager.AppSettings["path"];
var settings = ConfigurationManager.GetSection("ImageFormatsINeed");
When i didnt have the ImageFormatsINeed section i could get the path from AppSettings and it was working. But as soon as i added my ImageFormatsINeed section, everything stops working.
Now my question is how can i add custom sections in app.config that it will work, or should i just read my ImageInformation from some custom xml file or config file?
You have to use the tag <configSections> at the top in your app.config, for this case you should use the type AppSettingsSection
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ImageFormatsINeed" type="System.Configuration.AppSettingsSection" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
Then in your C# code:
NameValueCollection settings_section = ConfigurationManager.GetSection("ImageFormatsINeed") as NameValueCollection;
Console.WriteLine(settings_section["type1"]);
I'm trying to use a config file by directing there from App.config.
I have created a folder named Config inside my solution and created a new config file named Environment.config.
My App.Config looks as following:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<appSettings configSource="Config/Environment.config"/>
</configuration>
and the Environment.config looks as the following:
<appSettings>
<add key="URL" value="http://foo.aspx"/>
</appSettings>
I'm getting an error which says:
Result Message:
OneTimeSetUp: System.Configuration.ConfigurationErrorsException : Configuration system failed to initialize
----> System.Configuration.ConfigurationErrorsException : The configSource attribute must be a relative physical path, so the '/' character is not allowed. (D:\tfs\QA - Automation\Projects\ReportAppeal\ReportAppeal\bin\Debug\ReportAppeal.dll.config line 22)
I have tried to switch from "/" to "\" but got a different error.
Result Message:
System.Configuration.ConfigurationErrorsException : Unable to open configSource file 'Config\Environment.config'. (D:\tfs\QA - Automation\Projects\ReportAppeal\ReportAppeal\bin\Debug\ReportAppeal.dll.config line 22)
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
I'll probably need to change the way I'm directing the Environment.config file but I'm not sure how.
As the error says:
The configSource attribute must be a relative physical path
So you will need to change your key to a physical path, not a relative one:
<appSettings configSource="C:\Config\Environment.config"/>
Or just leave it under the root:
<appSettings configSource="Environment.config"/>
The class library project has a App.config file as given:
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<common>
<logging>
<factoryAdapter type="MyApp.Logging.NLog2FactoryAdapter, MyApp.Logging">
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.netfx40.xsd">
<extensions>
<add assembly="MyApp.Logging" />
</extensions>
<targets async="true">
<target type="Console" name="ConsoleTarget" layout="${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring:innerFormat=tostring:maxInnerExceptionLevel=8}" />
<target type="File" name="FileTarget" fileName="C:\Users\liangj\Desktop\log.log" layout="${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring:innerFormat=tostring:maxInnerExceptionLevel=8}" />
<target type="JsonNetwork" name="SplunkTarget" address="tcp4://log-staging.dbrs.local:10500" newLine="true" layout="${message} ${exception:format=tostring:innerFormat=tostring:maxInnerExceptionLevel=8}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="SplunkTarget,ConsoleTarget,FileTarget" />
</rules>
</nlog>
<appSettings>
<add key="AppVersion" value="2.1" />
</appSettings>
</configuration>
In the c# code, I have:
public static void WriteLog(string msg, IDictionary<string, object> metadata)
{
Configuration Configuration = ConfigurationManager.OpenExeConfiguration(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath);
string version = Configuration.AppSettings.Settings["AppVersion"].Value.ToString();
string LogTime = DateTime.Now.ToString("yyyy-M-dd H:mm:ss tt");
metadata["LogTime"] = LogTime;
Console.WriteLine(version );
Console.WriteLine(Logger.Log.ToString());
Logger.Log.InfoWithMetadata(msg, metadata);
}
The way this class library used is that it will be imported into PowerShell which adds custom cmdlets to it. When I open powerShell and execute the custom cmdlet, the open shows that the Logger is a taken as a default logger which doesn't do anything, but I do expect a proper logger to log to files.
I doubt that since this is a class library, it automatically generates a solutionName.dll.config file, which is not recognized by common.Logging, which may expects a exe.config instead?
I have the following task in my nant script:
<nunit2 verbose="true">
<formatter type="Plain" />
<test assemblyname="${output}\Test.dll" appconfig="${project.src.root}\Test\Test.config"/>
</nunit2>
Test.config is the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="nunit.framework" publicKeyToken="96d09a1eb7f44a77" culture="Neutral" />
<bindingRedirect oldVersion="2.5.3.9345" newVersion="2.2.8.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I get an error when i run this task saying could not load nunit.framework. I know nunit is not in the GAC (not strongly signed). Does Nunit have to be in the GAC for this task to work?
I provide the path to my NUnit binary during compilation. When I call nunit2, the reference to the framework is present and I don't get this error. Does this help?
<target name="unit.compile" depends="sharedClasses, helpers.compile" description="compiles the unit tests" >
<copy todir="build" flatten="true">
<fileset basedir="tools\NUnit-2.5.2.9222\framework">
<include name="nunit.framework.dll" />
</fileset>
</copy>
<csc target="library" output="build\${project::get-name()}.test.unit.dll" debug="${debug}">
<sources>
<include name="source\web\tests\unit\**\*.cs" />
<exclude name="source\web\tests\unit\**\AssemblyInfo.cs" />
</sources>
<references basedir="build" >
<include name="nunit.framework.dll" />
<include name="Microsoft.Practices.EnterpriseLibrary.Common.dll" />
<include name="Microsoft.Practices.EnterpriseLibrary.Data.dll" />
<include name="${project::get-name()}.sharedClasses.dll" />
<include name="${project::get-name()}.test.helpers.dll" />
</references>
</csc>
</target>
<target name="unit.test" depends="unit.compile, helpers.compile">
<copy file="configuration\Web.Config" tofile="build\${project::get-name()}.test.unit.dll.config" />
<copy file="configuration\ui_list.config" tofile="build\ui_list.test.config" />
<nunit2>
<test
assemblyname="build\${project::get-name()}.test.unit.dll"
appconfig="build\${project::get-name()}.test.unit.dll.config"
/>
<formatter type="Plain" />
</nunit2>
</target>
Set your Nant tasks to show with verbose output (often this means just adding 'verbose=true' to the applicable tasks) and see if you can verify the paths that it's trying to use to reference nunit.framework.dll.
It's very likely that the path to nunit.framework.dll in your project is a relative path that may not work when you try to run the task from NAnt via the command line. (for example, if your .csproj is nested in a folder but your Nant script is not, or if you're moving around the build outputs prior to testing).