How to programatically load a log4j2 XML config file AND have it take effect - log4j

I want to load a log4j2 XML configuration programmatically.
My config file is ok and the following two approaches work.
One, rename it to log4j2.xml and put it in the classpath (but I have multiple so this was for experiment). Two, do this (which works, but I'm maintaining some older code and would rather try and keep their mechanisms intact)
static {
File _l4 = new File (DATA_DIR + File.separator + LOG_CONFIG_FILENAME);
System.setProperty("log4j2.configurationFile", _l4.toURI().toString());
}
From what I've found on here, this should work.
FileInputStream fileInputStream = new FileInputStream(pConfigFilename);
ConfigurationSource configurationSource = new ConfigurationSource(fileInputStream);
Configurator.initialize(null, configurationSource);
It does seem to load the file as when I .toString() it, it shows that it has loaded the number of bytes - which happens to be the size of the config file. None of it works though. All logging goes to stdout. So it's loading, but not taking affect.

Configurator.initialize only works before the LoggerContext is created.
It should work in the static block were you set the log4j2.configurationFile property. If for some reason you need before loading the configuration file, you need to use Configurator.reconfigure.

Related

Loading JSON file not reflecting changes

I have a JSON file I use to store dialogue for a game. However, the changes I make to this JSON file are sometimes not reflected in my game even after hard reloads (I've been doing ctrl+shift+r or shift+F5 for this). I have made sure the changes to the JSON file are saved.
I have this.load.json('dialogue', 'assets/dialogue.json'); in preload(), and this.dialogue = this.cache.json.get('dialogue'); in create().
When I try copy+pasting the contents to a new different file (e.g. dialogue-2.json), and update my this.load.json() to reflect the new file name, the changes do get loaded.
The problem is that phaser doesn't automatic start the loading files, except in the preload function.
If you want to load files in other functions you need to call the start method of the LoadPlugin. Here the link to the official documentation.
The code should look something like this:
function create(){
// some code here ...
this.load.json(/* key and file...*/);
// start the loading of the enqueued files
this.load.start();
// some code here...
}
..., than the files should get loaded.
Update (copied form comments):
to check (and as a tempoary quickfix) if your problem, is a caching issue from the Webserver or browser or ..., you can load the file with a "dynamic" Url.
Just a load the file with a questionmark and random number added to the url, so that each call to the json uses aunique Url.
For Example like this:
this.load.json('dialogue', 'assets/dialogue.json?' + Math.random());
If this solves the problem, there is a caching problem. It could be in the browser, or simply caused by serviceworker or on the webserver.

Is there anyway to know that new files added to a folder in c#

Is there anyway to know that new files added to a folder in c# I can't use lastAccessTime and LastWriteTime and also I can't check if the size of the folder is changed because same size deleted files cause problems with size. So is there anyway to check a new file is added to a folder or not in c#
This can be done with a FileSystemWatcher, which provides events to notify you of FileSystem changes. Example:
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = pathToWatch;
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
Have a look at the documentation here: http://msdn.microsoft.com/de-de/library/system.io.filesystemwatcher.aspx
You can also set filters to watch only files, certain filenames etc.
Think carefully about the events you need to handle. If you watch created files, you probably want to handle deleted files as well.
You could use the FileSystemWatcher and respond to each change in the folder.
Because the events can be quite confusing (some programs overwrite a file, others delete first and then create etc.) it might be usefull to create a custom way of tracking changes.
E.g., you could create a hash of each file and compare the old and new hash every change or every 5 minutes or so. This way you can decide yourself what should cause the hash to change.
See: Creating hash for folder for an example.

using FileChooser to save a file with default filename

I wat to save a file.I use this.
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showSaveDialog(null);
But in the dialog I want to suggest a name for the file, so that the user only selects a directory for the given file.The name of the file is known already.So i want to suggest that filename.
ThankYou.
This is now fixed in Javafx 2.2.45 (bundled with java 7.0_45 now) and you can do what the OP is suggesing with the following property of fileChooser, setInitialFilename, used as such:
FileChooser myFile = new FileChooser();
myFile.setInitialFileName("Whatever_file_I_want.coolFile");
Now, I don't think there is anyway to STOP the user from choosing a different file, but at leas this will give them a default you want them to pick.
Initial file name providing - it is a thing, which requires to transfer your string (initial name) through native call, to the call of the native file chooser. It is a complex thing, and you can look at these issues about its implementing :
http://javafx-jira.kenai.com/browse/RT-16111 (main one)
http://javafx-jira.kenai.com/browse/RT-24588
http://javafx-jira.kenai.com/browse/RT-24612
They all have fix version lombard, so, they are fixed in JDK 8.
So, you can specify initial file name for a file, starting from JDK 8 (you can access it, downloading JDK early access).
Recently, I've tested this feature, and it is working.
There is a method setInitialName() or smth like that.
And, as I've mentioned, it is a complex thing, and you are not likely to be able to implement it by yourself (until you are able to build jfx).
So, the decision - to wait until JDK8 release, or to use early access builds. Or, to use your own implementation of file chooser.
Here's a workaround that worked for me:
you can use javafx.stage.DirectoryChooser to select a directory for the file you want to save and after saving create a new file in this directory with the default name and extension.
DirectoryChooser dc = new DirectoryChooser();
File file = dc.showDialog(null);
if (file != null) {
file = new File(file.getAbsolutePath() + "/dafaultFilename.extension");}

ClassLoader.getSystemResource(...).getPath() seems to return wrong path

I'm trying to wrap code that requires two *.db4o data files for easy use. I've added the data files to my eclipse .classpath by placing the files in ${project_dir}/res/ and adding the line:
<classpathentry kind="src" path="res"/>
to my .classpath.
I then defined a default constructor to my wrapper class that takes no arguments but goes and finds the paths to the *.db4o files (the paths are required by the compiled code I'm using to set things up). My approach for getting the paths is:
String datapath = ClassLoader.getSystemResource("resource_name").getPath();
This works great when I debug/run my code in eclipse. However when I export it as a jar, I can see that the *.db4o files are in the jar, as well as my compiled code, but the path returned to "datapath" is of the form:
datapath = ${pwd}/file:${absolute_path_to_jar}!/{resource_name}
Is there something about the resource being inside of the jar that prevents an absolute path from working? Also, why is the behavior different simply because the code and resources live in a jar file? One last note is that while my application is intended for wider use (from PIG, python, etc. code) I'm testing it from Matlab which is where I'm getting the odd value assigned to "datapath".
Thanks in advance for any responses.
getSystemResource() returns URL to resource. If your resource is zipped in a jar file then the URL will point into it (with the "!" notation). getPath() returns the "path" part of the URL, not always an actual file path. URL can be one of many things, not just a file.

log4 net Dynamic file name assigning

I want to know how to dynamically assign file name using Log4net .My application is such that 10 different files should be dynamically created based on user input ,and later based on the name the corresponding file name needs to be picked up and information written to it
For example in my application based on my buisness requirement for every xml file a corresponding log file with the same name as xml file should be created .Later whenever I do any modification to the xml file an entry needs to be in the corresponding log file
Please help . I having trouble to get control of the appropriate log to write it
Have not done this, but there are probably a number of ways of doing this, so this may not be the best way, but it should work
public OpenLogFile(string fileName)
{
log4net.Layout.ILayout layout = new log4net.Layout.PatternLayout("%d [%t]%-5p : - %m%n");;
log4net.Appender.FileAppender appender = new log4net.Appender.FileAppender(layout , filename);
appender.Threshold = log4net.Core.Level.Info;
log4net.Config.BasicConfigurator.Configure(appender);
}
Then just call OpenLogfile when you need to switch files.
You might need to tweak the layout or appender type.
A big disadvantage of this method is you losing the xml configuration and the ability to change settings at runtime. So a better way might be to configure your appender in the xml file to use a property
eg
file type="log4net.Util.PatternString" value="Logfiles\Log_For_%property{MyLogFileName}"
Then in your code you could change the property
log4net.GlobalContext.Properties["MyLogFileName"] = ...;
The tricky bit is to get log4net to reload itself. I haven't read the documentation of this, so I don't know if there is a way of forcing a reload. It might work if you just call log4net.Config.XmlConfigurator.ConfigureAndWatch again. Otherwise it should work if you opened the xml file and saved it again (without needing to change anything)
Hope this helps.

Resources