Whats wrong with my log4net configuration? - c#

I have an ASP.NET MVC app which has a bootstrapper class that configures log4net during application startup as follows:
public static void Configure(IApplicationContext applicationContext)
{
var appender = new log4net.Appender.FileAppender
{
Layout = new log4net.Layout.PatternLayout("%d [%t]%-5p %c [%x] <%X{auth}> - %m%n"),
File = applicationContext.GetLogFile().FullName
};
BasicConfigurator.Configure(appender);
}
I have checked that when I call the logging function later that the repository is configured:
LogManager.GetRepository().Configured
this returns true.
The location of applicationContext.GetLogFile().FullName exists and also has permissions set for any user to be able to create and modify files, so I don't quite understand why this fails to create a log file or output any data.
Now I know you can use config files and XML in the Web.config but because the log file location and configuration will change from site to site I need to do this in code.
Please can someone help me.

you should add an
appender.ActivateOptions();

Related

NLog not outputting text file

I have downloaded and installed the NuGet package NLog. I followed the tutorial, choosing to configure it through code, as follows:
public static void ConfigureLogger()
{
var config = new NLog.Config.LoggingConfiguration();
// target where to log to
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = path + #"\log.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
// rules for mapping loggers to targets
// minimum and maximum log levels for logging targets
config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole);
config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logfile);
// apply config
NLog.LogManager.Configuration = config;
}
Within the application code, each class gets its own instance, as recommended in the tutorial:
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
I find that it is not writing the text file to the specified directory. I have read some troubleshooting advice, but I cannot find the file "NLog.config".
Are you using .net core? On both .net and .net core you need what's referenced here for nlog:
https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3
Create nlog.config (lowercase all) file in the root of your project.
So you don't find out because you have not created it. There are more things to do.
In your code configuration, you need to execute the function somewhere. Are you calling it from your Startup.cs or any other entry point depending on the platform?

C# - How to use another project logging configuration into current project?

I have 12 projects in my solution file. There are most Windows services (ServiceProj_1, ServiceProj_2, ...) and one project is of web application (WebApp). I use log4net for logging. WebApp and ServiceProject_1, ServiceProj_2, ... have log4net configuration into web.config and app.config files respectively. We have implemented a DMZ, so the WebApp is only exposed to the other people. Now there is a requirement to use logging of those windows service projects instead of WebApp.
I have come to know that I can create a custom appender and make it possible. The catch is, there are lots of lines already written into WebApp to log a LogMessage into log file so we cannot touch those lines.
I have no idea what to do and how to do. Need help.
If the description is not understandable then please let me know I will try to explain more.
You can specify the config file and load it dynamically...
Here my config file is found at the location of FullConfigFilePath.
private Configuration Config
{
get
{
if (_Config != null) return _Config;
_Config = ConfigurationManager.OpenMappedExeConfiguration(
new ExeConfigurationFileMap()
{
ExeConfigFilename = FullConfigFilePath
}, ConfigurationUserLevel.None);
return _Config;
}
}
Once the config is loaded you can access the values from there....
For instance.....
private string BaseUrl
{
get
{
return this.Config.AppSettings.Settings["MyConfigSetting"].Value;
}
}
Hopefully you can tweak and use this sort of approach for your needs.

Generate an exe with predefinied settings

I do apologise if i didn't asked correctly in the title.. i don't know how to ask or what to call for what i need.
-
Let's say that i have a simple Application called "TestApp" written in C#.
Inside that application, i have the next variables:
int clientid = 123;
string apiurl = "http://somesite/TestApp/api.php";
When i have a new client, i need to create a new special TestApp.exe just for him, changing the 'clientid' variable inside the code.
It's possible to automate this process? To change that variable automatically and export an exe without for me to interfere with the process?
-
I asked this because i think/or i'm sure that it's possible because of the next popular examples:
http://download.cnet.com/2701-20_4-1446.html?tag=sideBar;downloadLinks
[ It creates a special .exe with a predefinied link from where to download the real file ]
http://torrent2exe.com/
[ It's embedding the .torrent file to a special .exe just with some custom variables changed, like torrent name or download size ]
Again, i do apologise if i didn't asked my question correctly and for my bad english, trying my best.
So you have two parts to your question:
You want to have variables inside the program based on client for your app
You want to automate the process of making the settings changes.
To make custom settings:
Use AppSettings.
First, add a reference to System.Configuration assembly.
In your app.config file:
<configuration>
<appSettings>
<add key="ClientID" value="123" />
<add key="ApiUrl" value="http://somesite/TestApp/api.php" />
</appSettings>
</configuration>
In your code, to read the settings:
using System;
using System.Configuration;
class Program
{
private static int clientID;
private static string apiUrl;
static void Main(string[] args)
{
// Try to get clientID - example that this is a required field
if (!int.TryParse( ConfigurationManager.AppSettings["ClientID"], out clientID))
throw new Exception("ClientID in appSettings missing or not an number");
// Get apiUrl - example that this isn't a required field; you can
// add string.IsNullOrEmpty() checking as needed
apiUrl = ConfigurationManager.AppSettings["apiUrl"];
Console.WriteLine(clientID);
Console.WriteLine(apiUrl);
Console.ReadKey();
}
}
More about AppSettings on MSDN
To automate the creation of settings:
This all depends on how complex you want to get.
When you build your project, your app.config file becomes TestApp.exe.config
You can use ConfigurationManager class to write Config files.
Further, you can write a little Exe that writes the config file with custom settings and execute it as part of a build action. Lots of ways to accomplish automation which depend on how you intend to deploy your application.
A quick example of writing an app.config file appSettings section programmatically:
public static void CreateOtherAppSettings()
{
Configuration config =
ConfigurationManager.OpenExeConfiguration("OtherApp.config");
config.AppSettings.Settings.Add("ClientID", "456");
config.AppSettings.Settings.Add("ApiUrl", "http://some.other.api/url");
config.Save(ConfigurationSaveMode.Modified);
}

Editing a custom configuration section in an installer class

I am trying to update a custom configuration section of a web.config file during the installation of my product in a custom action. I wanted to use the actual configration classes to do this however when the installer runs it loads my installer class but then the
Configuration.GetSection throw a File Not Found exception as it is trying to load my custom section class from the windows system directory. I managed to get this to work by copying the required assemblies into the windows system directory but this is not an ideal solution as I cannot guarantee I will always have access to that directory.
How else can I solve this problem?
My update code looks like this
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public override void Install(System.Collections.IDictionary stateSaver)
{
//some code here
webConfig = WebConfigurationManager.OpenWebConfiguration("MyService");
MyCustomSection mySection = webconfig.GetSection("MyCustomSection") //<--File Not Found: CustomConfigSections.dll
//Update config section and save config
}
}
My config file looks like this
<configuration>
<configSections>
<section name="myCustomSection" type="CustomConfigSections.MyCustomSection, CustomConfigSections" />
</configSections>
<myCustomSection>
<!-- some config here -->
</myCustomSection>
</configuration>
Hope you would understand the answer the way it is intended.
Assuming that you have setup the installer to have your project output. If Not
Right Click on installer Project click add->Project Output->select your project
and then you can continue using your code.
Moreover if you are using dll except the .net Ones make sure to change there
properties to copylocal = true
If You want to read the element Before Installation use BeforeInstall Event
Handler and try reading your file. ihope your problem will be solved
If in case You want to read the element after installation Right Click On
installer project Click view->customActions->On Install Click Add Custom Action
->Select Application Folder -> Select Primary output from your project and click
ok .
Now Click on primary output and press F4 and in Custom Action Data write
/DIR="[TARGETDIR]\"
and after that write your code as follows.
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
public ProjectInstaller()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
this.AfterInstall += new InstallEventHandler(ProjectInstaller_AfterInstall);
}
void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
{
string path = this.Context.Parameters["DIR"] + "YourFileName.config";
// make sure you replace your filename with the filename you actually
// want to read
// Then You can read your config using XML to Linq Or you can use
// WebConfigurationManager whilst omitting the .config from the path
}

How do I specify the name of my application's App.config file in WPF?

This is very frustrating... I can set the Configuration File for a Windows Forms Application just fine. Consider this:
public static void Main(){
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #"SharedAppConfig.config");
//do other things
}
However, in a WPF application, this doesn't seem to work! If I set this value, the value of the AppDomain.CurrentDomain.SetupInformation.ConfigurationFile property is correct, but any calls to that configuration file while debugging yield no results. There are WCF configuration settings in an App.config that I need to share between application, so this is my proposed solution. Is it possible to dynamically set the location of my config file in WPF?
Help! Thanks!
You should be able to do something along the lines of:
using System.Configuration;
public class TryThis
{
Configuration config = ConfigurationManager.OpenExeConfiguration("C:\PathTo\app.exe");
public static void Main()
{
// Get something from the config to test.
string test = config.AppSettings.Settings["TestSetting"].Value;
// Set a value in the config file.
config.AppSettings.Settings["TestSetting"].Value = test;
// Save the changes to disk.
config.Save(ConfigurationSaveMode.Modified);
}
}
NOTE: This will attempt to open a file named app.exe.config at C:\PathTo. This also REQUIRES that a file exists at the same path with the name "app.exe". The "app.exe" file can just be an empty file though. For your case I'd almost make a shared "Config.dll" library that would handle the config file.
~md5sum~
Is this on the service side or the client side? If on the service side, it is often the case that the service is running in its own AppDomain, so that if you set AppDomain.CurrentDomain.SetData(...) it won't apply to the service configuration.
I'm not entirely sure how to get around this, but you should be able to control the service's configuration by implementing your own ServiceHost.

Categories

Resources