Access log4j2 map lookup in a custom lookup plugin - plugins

I have a custom lookup plugin that needs to access a value from the standard map plugin (map:contextName) to do further processing. How can I do this?

Since I'm only interested in the context name I found that I could just do:
LoggerContext ctx = (LoggerContext) LogManager.getContext();
String contextName = ctx.getName();

Related

Disable logging on FileConfigurationSourceChanged - LogEnabledFilter

I want Administrators to enable/disable logging at runtime by changing the enabled property of the LogEnabledFilter in the config.
There are several threads on SO that explain workarounds, but I want it this way.
I tried to change the Logging Enabled Filter like this:
private static void FileConfigurationSourceChanged(object sender, ConfigurationSourceChangedEventArgs e)
{
var fcs = sender as FileConfigurationSource;
System.Diagnostics.Debug.WriteLine("----------- FileConfigurationSourceChanged called --------");
LoggingSettings currentLogSettings = e.ConfigurationSource.GetSection("loggingConfiguration") as LoggingSettings;
var fdtl = currentLogSettings.TraceListeners.Where(tld => tld is FormattedDatabaseTraceListenerData).FirstOrDefault();
var currentLogFileFilter = currentLogSettings.LogFilters.Where(lfd => { return lfd.Name == "Logging Enabled Filter"; }).FirstOrDefault();
var filterNewValue = (bool)currentLogFileFilter.ElementInformation.Properties["enabled"].Value;
var runtimeFilter = Logger.Writer.GetFilter<LogEnabledFilter>("Logging Enabled Filter");
runtimeFilter.Enabled = filterNewValue;
var test = Logger.Writer.IsLoggingEnabled();
}
But test reveals always the initially loaded config value, it does not change.
I thought, that when changing the value in the config the changes will be propagated automatically to the runtime configuration. But this isn't the case!
Setting it programmatically as shown in the code above, doesn't work either.
It's time to rebuild Enterprise Library or shut it down.
You are right that the code you posted does not work. That code is using a config file (FileConfigurationSource) as the method to configure Enterprise Library.
Let's dig a bit deeper and see if programmatic configuration will work.
We will use the Fluent API since it is the preferred method for programmatic configuration:
var builder = new ConfigurationSourceBuilder();
builder.ConfigureLogging()
.WithOptions
.DoNotRevertImpersonation()
.FilterEnableOrDisable("EnableOrDisable").Enable()
.LogToCategoryNamed("General")
.WithOptions.SetAsDefaultCategory()
.SendTo.FlatFile("FlatFile")
.ToFile(#"fluent.log");
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
var defaultWriter = new LogWriterFactory(configSource).Create();
defaultWriter.Write("Test1", "General");
var filter = defaultWriter.GetFilter<LogEnabledFilter>();
filter.Enabled = false;
defaultWriter.Write("Test2", "General");
If you try this code the filter will not be updated -- so another failure.
Let's try to use the "old school" programmatic configuration by using the classes directly:
var flatFileTraceListener = new FlatFileTraceListener(
#"program.log",
"----------------------------------------",
"----------------------------------------"
);
LogEnabledFilter enabledFilter = new LogEnabledFilter("Logging Enabled Filter", true);
// Build Configuration
var config = new LoggingConfiguration();
config.AddLogSource("General", SourceLevels.All, true)
.AddTraceListener(flatFileTraceListener);
config.Filters.Add(enabledFilter);
LogWriter defaultWriter = new LogWriter(config);
defaultWriter.Write("Test1", "General");
var filter = defaultWriter.GetFilter<LogEnabledFilter>();
filter.Enabled = false;
defaultWriter.Write("Test2", "General");
Success! The second ("Test2") message was not logged.
So, what is going on here? If we instantiate the filter ourselves and add it to the configuration it works but when relying on the Enterprise Library configuration the filter value is not updated.
This leads to a hypothesis: when using Enterprise Library configuration new filter instances are being returned each time which is why changing the value has no effect on the internal instance being used by Enterprise Library.
If we dig into the Enterprise Library code we (eventually) hit on LoggingSettings class and the BuildLogWriter method. This is used to create the LogWriter. Here's where the filters are created:
var filters = this.LogFilters.Select(tfd => tfd.BuildFilter());
So this line is using the configured LogFilterData and calling the BuildFilter method to instantiate the applicable filter. In this case the BuildFilter method of the configuration class LogEnabledFilterData BuildFilter method returns an instance of the LogEnabledFilter:
return new LogEnabledFilter(this.Name, this.Enabled);
The issue with this code is that this.LogFilters.Select returns a lazy evaluated enumeration that creates LogFilters and this enumeration is passed into the LogWriter to be used for all filter manipulation. Every time the filters are referenced the enumeration is evaluated and a new Filter instance is created! This confirms the original hypothesis.
To make it explicit: every time LogWriter.Write() is called a new LogEnabledFilter is created based on the original configuration. When the filters are queried by calling GetFilter() a new LogEnabledFilter is created based on the original configuration. Any changes to the object returned by GetFilter() have no affect on the internal configuration since it's a new object instance and, anyway, internally Enterprise Library will create another new instance on the next Write() call anyway.
Firstly, this is just plain wrong but it is also inefficient to create new objects on every call to Write() which could be invoked many times..
An easy fix for this issue is to evaluate the LogFilters enumeration by calling ToList():
var filters = this.LogFilters.Select(tfd => tfd.BuildFilter()).ToList();
This evaluates the enumeration only once ensuring that only one filter instance is created. Then the GetFilter() and update filter value approach posted in the question will work.
Update:
Randy Levy provided a fix in his answer above.
Implement the fix and recompile the enterprise library.
Here is the answer from Randy Levy:
Yes, you can disable logging by setting the LogEnabledFiter. The main
way to do this would be to manually edit the configuration file --
this is the main intention of that functionality (developers guide
references administrators tweaking this setting). Other similar
approaches to setting the filter are to programmatically modify the
original file-based configuration (which is essentially a
reconfiguration of the block), or reconfigure the block
programmatically (e.g. using the fluent interface). None of the
programmatic approaches are what I would call simple – Randy Levy 39
mins ago
If you try to get the filter and disable it I don't think it has any
affect without a reconfiguration. So the following code still ends up
logging: var enabledFilter = logWriter.GetFilter();
enabledFilter.Enabled = false; logWriter.Write("TEST"); One non-EntLib
approach would just to manage the enable/disable yourself with a bool
property and a helper class. But I think the priority approach is a
pretty straight forward alternative.
Conclusion:
In your custom Logger class implement a IsLoggenabled property and change/check this one at runtime.
This won't work:
var runtimeFilter = Logger.Writer.GetFilter<LogEnabledFilter>("Logging Enabled Filter");
runtimeFilter.Enabled = false/true;

Generate code from Metamodel via XTend

I have an Ecore model in an existing EMF project and want to print the name of all containing classes into a text file via XTend. How do you achieve this? The XTend examples don't show how to use a model and get Information out of it.
If you only need the EClasses of your Meta-Model then you can get them from your Model Package:
YourEMFModelPackage.eINSTANCE.getEClassifiers() which returns a EList<EClassifier>. Since an EClass is an EClassifier you get all your EClass implementations org.eclipse.emf.ecore.impl.EClassImpl.
For type-safety concerns you probably check if this List only contains EClasses, since all your EDataTypes are also EClassifier.
So this should to the Trick:
EcoreUtil.getObjectsByType(YourEMFModelPackage.eINSTANCE.getEClassifiers(), EcorePackage.eINSTANCE.getEClass())
or:
List<EClass> allEClasses = YourEMFModelPackage.eINSTANCE.getEClassifiers().stream().filter(p -> EClass.class.isInstance(p)).map(m -> EClass.class.cast(m)).collect(Collectors.toList());
Update:
If you don't have your Model-Code generated you're still able to do this, you only need to load your Ecore into a Resource:
ResourceSet resourceSet = new ResourceSetImpl();
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore",
new EcoreResourceFactoryImpl());
Resource resource = resourceSet.getResource(
URI.createFileURI(
"../path/to/your/Ecore.ecore"),
true);
EPackage model = (EPackage) resource.getContents().get(0);
If you have the EPackage then you get your EClass like mentioned above

Elasticsearch scala elastic4s settings from property file

is there a way how to pass settings to elastic4s from property file? The following way works but it is not flexible in munltienvironment:
val settings = ImmutableSettings.settingsBuilder().put("cluster.name","elasticsearch").build()
val client = ElasticClient.remote(settings, "154.86.209.242" -> 9300, "153.89.219.241" -> 9300)
I tried java configuration file elasticsearch.yaml as mantioned in java doc but that doesn't work.
Any suggestion here?
You can do this using the same method you would for the Java client. The ImmutableSettings is a Java Client class not something that is specific to elastic4s.
To load your properties file from the classpath, eg if you have something in src/main/resources/com/package/settings.props
ImmutableSettings.settingsBuilder().loadFromClasspath("/com/package/mysettings.yaml")
Or if you want to load from an input stream:
ImmutableSettings.settingsBuilder().loadFromStream(myinputstream)
There are other methods too, just check out the ImmutableSettings.settingsBuilder object.

Magnolia HierarchyManager and Content are depreciated. How do I replicate functionality using Session and jcrNode?

I'm trying to do some logic in my Spring controller where I route to a website node based on the template used in another website node.
I can use LifeTimeJCRSessionUtil.getHierarchyManager("website").getContent("mynodepath").getTemplate() to do this, but I see that the HierarchyManager and Content classes are depreciated.
I looked at the Session class, but I have thus far been unable to figure out how to get the Template id based on the jcrNode.
You can use instead:
javax.jcr.Session jcrSession = LifeTimeJCRSessionUtil.getSession("website");
Node mynode = jcrSession.getNode("/my/node/path");
info.magnolia.cms.core.MetaData metaData = info.magnolia.jcr.util.MetaDataUtil.getMetaData(mynode);
String template = metaData.getTemplate();
Basically, instead of getHierarchyManager("website").getContent("mynodepath") you should use
getSession("website").getNode("/my/node/path").

Not able to do this.Context.Users.Load()

http://msdn.microsoft.com/en-us/library/bb896376.aspx here it says about a load method
this.context = new MyEntities();
this.Context.Users.
but i am not able to do this.Context.Users.Load()
i am not able to find the method load
what can i do?
If it doesn't offer you Load method it means that Users is not EntityCollection<User>. It is either ObjectQuery<User>, ObjectSet<User> or DbSet<User>. Instead of Load use:
var data = this.context.Users.ToList();
It also answers question what should you do? You should learn to use your IDE to identify correct type before you start searching in documentation.