Jasypt with Spring ... Logger Config - spring

While using Jasypt in Spring the logger level in the load properties method of the PropertiesLoaderSupport class is set to Info
protected void loadProperties(Properties props) throws IOException {
if (this.locations != null) {
for (Resource location : this.locations) {
if (logger.isInfoEnabled()) {
logger.info("Loading properties file from " + location);
}
The above code block returns true while using Jasypt whereas it returns false with Spring due to while I get lot of unwanted log message.
Can somebody suggest how can I make it to return false through configurations .
I am using log4j for my application as well .
Thanks

I was able to find out the result after a lot of search ... To resolve this issue we have to set the Logger properties for Jasypt in the Logger configuration being used for the application . For example
name="log4j.logger.org.jasypt">ERROR
That will resolve the issue .

Related

Problem with connection to Neo4j test container using Spring boot 2 and JUnit5

Problem with connection to Neo4j test container using Spring boot 2 and JUnit5
int test context. Container started successfully but spring.data.neo4j.uri property has a wrong default port:7687, I guess this URI must be the same when I call neo4jContainer.getBoltUrl().
Everything works fine in this case:
#Testcontainers
public class ExampleTest {
#Container
private static Neo4jContainer neo4jContainer = new Neo4jContainer()
.withAdminPassword(null); // Disable password
#Test
void testSomethingUsingBolt() {
// Retrieve the Bolt URL from the container
String boltUrl = neo4jContainer.getBoltUrl();
try (
Driver driver = GraphDatabase.driver(boltUrl, AuthTokens.none());
Session session = driver.session()
) {
long one = session.run("RETURN 1",
Collections.emptyMap()).next().get(0).asLong();
assertThat(one, is(1L));
} catch (Exception e) {
fail(e.getMessage());
}
}
}
But SessionFactory is not created for the application using autoconfiguration following to these recommendations - https://www.testcontainers.org/modules/databases/neo4j/
When I try to create own primary bean - SessionFactory in test context I get the message like this - "URI cannot be returned before the container is not loaded"
But Application runs and works perfect using autoconfiguration and neo4j started in a container, the same cannot be told about the test context
You cannot rely 100% on Spring Boot's auto configuration (for production) in this case because it will read the application.properties or use the default values for the connection.
To achieve what you want to, the key part is to create a custom (Neo4j-OGM) Configuration bean. The #DataNeo4jTest annotation is provided by the spring-boot-test-autoconfigure module.
#Testcontainers
#DataNeo4jTest
public class TestClass {
#TestConfiguration
static class Config {
#Bean
public org.neo4j.ogm.config.Configuration configuration() {
return new Configuration.Builder()
.uri(databaseServer.getBoltUrl())
.credentials("neo4j", databaseServer.getAdminPassword())
.build();
}
}
// your tests
}
For a broader explanation have a look at this blog post. Esp. the section Using with Neo4j-OGM and SDN.

Spring-boot: Servlet Environment being logged despite Log level

Recently upgraded from Spring-Boot 1.5.6.RELEASE to 1.5.8.RELEASE
On doing so, we noticed the environment was being logged out as "DEBUG" and category "StandardServletEnvironment".
However, the application.properties file does not specify logging at DEBUG level. Even explicitly setting a level of warning or error for that class does not make a difference.
The code that is doing the logging is in the constructor of org.springframework.core.env.AbstractEnvironment:
public AbstractEnvironment() {
customizePropertySources(this.propertySources);
if (logger.isDebugEnabled()) {
logger.debug("Initialized " + getClass().getSimpleName() + " with PropertySources " + this.propertySources);
}
}
Debug is not enabled, yet it logs. It seems as if it is doing this before it reads the log levels from application.properties.
Is there any explanation for this, or a way around this?
The application.properties has:
logging.level.root=INFO
logging.level.com.mycompany=DEBUG
In the code, I see a comment about logging initialization being deferred.
I managed to suppress this error by creating my own WebApplicationInitializer class, in which I explicitly set the offending log-category to a log-level of INFO
class MyWebApplicationInitializer implements WebApplicationInitializer{
#Override
void onStartup(ServletContext servletContext) throws ServletException {
String category = 'org.springframework.web.context.support.StandardServletEnvironment'
ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(category)
logbackLogger.setLevel(ch.qos.logback.classic.Level.INFO)
logbackLogger.info("Setting log level in ${this.class.name}, for ${logbackLogger.name}, to ${logbackLogger.level}")
}
It feels like a hack. So, if someone has a better answer, please post.

java.io.FileNotFoundException:/BOOT-inf/classes!/templates/

i am useing springboot create a project ,it's no error run idea,but, run app.jar file ,it's run Exception like this
java.io.FileNotFoundException: class path resource [templates/] cannot be resol
ed to absolute file path because it does not reside in the file system: jar:fil
:/E:/projects/help/target/zhx-help-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/templa
es/
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:21
)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(Ab
tractFileResolvingResource.java:52)
at org.springframework.ui.freemarker.FreeMarkerConfigurationFactory.get
emplateLoaderForPath(FreeMarkerConfigurationFactory.java:338)
at org.springframework.ui.freemarker.FreeMarkerConfigurationFactory.cre
teConfiguration(FreeMarkerConfigurationFactory.java:290)
at org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer
afterPropertiesSet(FreeMarkerConfigurer.java:116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getO
ject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegist
y.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetB
an(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBea
(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory
springboot version :1.5.2
useing spring-data-jpa
I see you use freemarker. In spring boot you cannot use the normal File approach to get your templates because they are not accessible when you run an executable JAR (File cannot be loaded as a resource when inside the JAR)
Use the following approach to load your templates folder:
cfg.setTemplateLoader(new ClassTemplateLoader(getClass().getClassLoader(), "templates"));
Full example:
#Configuration
public class FreemarkerConfiguration {
#Bean
public freemarker.template.Configuration freemarkerConfig() throws IOException {
freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
cfg.setTemplateLoader(new ClassTemplateLoader(getClass().getClassLoader(), "templates"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
return cfg;
}
}
If you are using jersey with spring boot, Jersey doesn't work well with Spring Boot. The reason for this error is, jersey is not able to auto discover all the rest resources. To fix this, register all the resources explicitly, registering package doesn't work. Hope this issue will be fixed in future versions of jersey.
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(Resource1.class);
register(Resource2.class);
register(Resource3.class);
}
}
FreeMarkerConfigurationFactory.class
protected TemplateLoader getTemplateLoaderForPath(String templateLoaderPath) {
if(this.isPreferFileSystemAccess()) {
try {
Resource ex = this.getResourceLoader().getResource(templateLoaderPath);
File file = ex.getFile();
if(this.logger.isDebugEnabled()) {
this.logger.debug("Template loader path [" + ex + "] resolved to file path [" + file.getAbsolutePath() + "]");
}
return new FileTemplateLoader(file);
} catch (IOException var4) {
if(this.logger.isDebugEnabled()) {
this.logger.debug("Cannot resolve template loader path [" + templateLoaderPath + "] to [java.io.File]: using SpringTemplateLoader as fallback", var4);
}
return new SpringTemplateLoader(this.getResourceLoader(), templateLoaderPath);
}
} else {
this.logger.debug("File system access not preferred: using SpringTemplateLoader");
return new SpringTemplateLoader(this.getResourceLoader(), templateLoaderPath);
}
}
so make log lever info
<logger name="org.springframework.web" level="INFO"/>

One Tomcat two spring application (war) two seperate logging configurations

As mentioned in the title I have two applications with two different logging configurations. As soon as I use springs logging.file setting I can not seperate the configurations of both apps.
The problem worsens because one app is using logback.xml and one app is using log4j.properties.
I tried to introduce a new configuration parameter in one application where I can set the path to the logback.xml but I am unable to make the new setting work for all logging in the application.
public static void main(String[] args) {
reconfigureLogging();
SpringApplication.run(IndexerApplication.class, args);
}
private static void reconfigureLogging() {
if (System.getProperty("IndexerLogging") != null && !System.getProperty("IndexerLogging").isEmpty()) {
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
// Call context.reset() to clear any previous configuration, e.g. default
// configuration. For multi-step configuration, omit calling context.reset().
System.out.println("SETTING: " + System.getProperty("IndexerLogging"));
System.out.println("SETTING: " + System.getProperty("INDEXER_LOG_FILE"));
context.reset();
configurator.doConfigure(System.getProperty("IndexerLogging"));
} catch (JoranException je) {
System.out.println("FEHLER IN CONFIG");
}
logger.info("Entering application.");
}
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
reconfigureLogging();
return application.sources(applicationClass);
}
The above code works somehow. But the only log entry which is written to the logfile specified in the configuration, which ${IndexerLogging} points to, is the entry from logger.info("Entering application."); :(
I don't really like to attach that code to every class which does some logging in the application.
The application has to be runnable as tomcat deployment but also as spring boot application with integrated tomcat use.
Any idea how I can set the path from ${IndexerLogging} as the path to read the configuration file when first configuring logging in that application?
Take a look at https://github.com/qos-ch/logback-extensions/wiki/Spring you can configure the logback config file to use.

Log4j2 in a spring web app with servlet 3.0

I need to change the default location of log4j2 configuration file. I followed the documentation here
https://logging.apache.org/log4j/2.x/manual/webapp.html
But the only file log4j2 can see is log4j2.xml in the classpath. otherwise I get "no log4j2 configuration file found"
I tried:
-1 setting context parameters
-2 setting system property Log4jContextSelector to "org.apache.logging.log4j.core.selector.JndiContextSelector". and using the JNDI selector
as described here
https://logging.apache.org/log4j/2.x/manual/webapp.html#ContextParams
-3 lookups: web, env, sys, ctx and bundle. the first 4 failed only bundle worked but you can only lookup inside the classpath.
-4 set isLog4jAutoInitializationDisabled to true, and I am not sure how to configure the filter in this case. If I include them in the web.xml the app will not deploy.
jar in the project
./WEB-INF/lib/log4j-jcl-2.4.1.jar
./WEB-INF/lib/log4j-core-2.4.1.jar
./WEB-INF/lib/log4j-slf4j-impl-2.4.1.jar
./WEB-INF/lib/log4j-api-2.4.1.jar
In my situation with .propeties file I use code shown below
#Plugin(name = "LogsConfigurationFactory", category = ConfigurationFactory.CATEGORY)
public class CustomLogsConfigurationFactory extends PropertiesConfigurationFactory {
#Override
public Configuration getConfiguration(String name, URI configLocation) {
File propFile = new File("/path_to/log4j2.properties");
return super.getConfiguration(name, propFile.toURI());
}
#Override
protected String[] getSupportedTypes() {
return new String[] {".properties", "*"};
}
}
I think you can change CustomLogsConfigurationFactory on XmlConfigurationFactory, and change return typse in getSupportedTypes method. I hope this will help you.

Resources