why isn't nlog saving a bad request url? - asp.net-mvc

I use ASP.NET Core and NLog.Web.AspNetCore (4.3.1). NLog isn't saving a bad request url - why?
That is mine NLog.config:
<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}/nlog.txt"
layout="${longdate} url: ${aspnet-request-url} | ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Warn" writeTo="logfile"/>
</rules>
</nlog>
When I have a 404 error nlog is saving:
2017-05-11 20:07:34.2466 url: | My error message
Url above is empty - why?
My Configure method in Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// .....
app.UseExceptionHandler("/Error/ApplicationError");
app.UseStatusCodePagesWithReExecute("/Error/Error/{0}");
// .....
loggerFactory.AddNLog();
app.AddNLogWeb();
// ......
}
My Error controller:
public class ErrorController : Controller
{
private readonly ILogger<ErrorController> _logger;
public ErrorController(ILogger<ErrorController> logger)
{
_logger = logger;
}
public IActionResult ApplicationError()
{
return View();
}
[Route("/Error/Error/{statusCode}")]
public IActionResult Error(int statusCode)
{
_logger.LogError("My error message");
return View(statusCode);
}
}

Try adding the AspnetCore extensions to your NLog configuration:
<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
...
</nlog>
See the NLog AspnetCore documentation for more info.

Related

Log every request to web api method to file

My requirements are to add logging to every request and response and errors to a file. I have tried this,
public class LogRequestAndResponseHandler : DelegatingHandler
{
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// log request body
string requestBody = await request.Content.ReadAsStringAsync();
Log.Info(requestBody);
// let other handlers process the request
var result = await base.SendAsync(request, cancellationToken);
if (result.Content != null)
{
// once response body is ready, log it
var responseBody = await result.Content.ReadAsStringAsync();
Log.Info(responseBody);
}
return result;
}
}
Added this it to WebApiConfig of MVC5 as following,
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
log4net.Config.XmlConfigurator.Configure();
config.MessageHandlers.Add(new LogRequestAndResponseHandler());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Web config has this section,
<log4net>
<!-- file appender -->
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:/logs/my_log_file.log"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<maxSizeRollBackups value="30"/>
<datePattern value=".yyyy-MM-dd"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
Nothing is being added to file and there are no errors, is there anything I am doing wrong, it creates the file but no logging ever ?

Spring data elasticsearch CRUD configuration

I am facing problem while configuring the spring data elasticsearch, I followed the procedure mentioned here Spring bean configuration for Crud Repositories. But I am getting error:
Exception in thread "main"
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'customerService': Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'customerRepo': Cannot resolve reference to
bean 'elasticsearchTemplate' while setting bean property
'elasticsearchOperations'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'elasticsearchTemplate' defined in class path
resource [spring-repository.xml]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException:
Could not instantiate bean class
[org.springframework.data.elasticsearch.core.ElasticsearchTemplate]:
Constructor threw exception; nested exception is
java.lang.NoSuchMethodError:
com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
Here is the code:
CustomerService.java
#Service
public class CustomerService {
#Resource
CustomerRepo custRepo;
public void save(Customer cust) {
custRepo.save(cust);
}
}
Customer.java
#Document(
indexName = "Customer", type = "cust"
)
public class Customer {
#Id
private String id;
private String name;
public Customer(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
CustomerRepo.java
public interface CustomerRepo extends ElasticsearchRepository<Customer, String> {
}
MainClass.java
public class MainClass {
public static void main(String args[]) {
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring-customer.xml"});
CustomerService cust = (CustomerService)context.getBean("CustomerService");
Customer customer = new Customer("test_name");
cust.save(customer);
}
}
spring-customer.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.elasticsearch" />
<import resource="spring-repository.xml"/>
</beans>
spring-repository.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch
http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<elasticsearch:transport-client id="client" cluster-nodes="xx.xx.xx.xx:9200" />
<bean name="elasticsearchTemplate"
class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean>
<elasticsearch:repositories
base-package="com.elasticsearch.repositories" />
I don't know why it is not working. Please help me out.
It worked finally, after modifying these files:
1) spring-customer.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.elasticsearch.repositories" />
<import resource="spring-repository.xml"/>
<bean id="customerService" class="com.elasticsearch.CustomerService" scope="prototype" >
<property name="custRepo" ref="custRepo"></property>
</bean>
</beans>
2) Changing port no. from 9200 to 9300 in spring-repository.xml. As 9200 is for http, where as 9300 is for node to node communication.
3) Adding getter and setter for custRepo in CustomerService.java file.

Spring Security 3.2.3 RELEASE with JavaConfig

I have a Spring Security configured in XML that works just fine. Now, I'm trying to have it expressed in JavaConfig only so as to get rid of the XML configuration altogether.
I've looked at the reference documentation, and at many blogs and support requests, but I still cannot find the solution.
It gives me the following exception:
Could not autowire field: private org.springframework.security.web.FilterChainProxy
com.thalasoft.learnintouch.rest.config.WebTestConfiguration.springSecurityFilterChain;
Pitifully I resorted to post my own request here...
The code:
#Configuration
#ComponentScan(basePackages = { "com.thalasoft.learnintouch.rest" })
public class WebTestConfiguration {
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private FilterChainProxy springSecurityFilterChain;
}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
public class WebInit implements WebApplicationInitializer {
private static Logger logger = LoggerFactory.getLogger(WebInit.class);
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerListener(servletContext);
registerDispatcherServlet(servletContext);
registerJspServlet(servletContext);
}
private void registerListener(ServletContext servletContext) {
// Create the root application context
AnnotationConfigWebApplicationContext appContext = createContext(ApplicationConfiguration.class, WebSecurityConfiguration.class);
// Set the application display name
appContext.setDisplayName("LearnInTouch");
// Create the Spring Container shared by all servlets and filters
servletContext.addListener(new ContextLoaderListener(appContext));
}
private void registerDispatcherServlet(ServletContext servletContext) {
AnnotationConfigWebApplicationContext webApplicationContext = createContext(WebConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
dispatcher.setLoadOnStartup(1);
Set<String> mappingConflicts = dispatcher.addMapping("/");
if (!mappingConflicts.isEmpty()) {
for (String mappingConflict : mappingConflicts) {
logger.error("Mapping conflict: " + mappingConflict);
}
throw new IllegalStateException(
"The servlet cannot be mapped to '/'");
}
}
private void registerJspServlet(ServletContext servletContext) {
}
private AnnotationConfigWebApplicationContext createContext(final Class... modules) {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(modules);
return appContext;
}
}
#Configuration
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
CustomAuthenticationProvider customAuthenticationProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
#Bean
public DelegatingFilterProxy springSecurityFilterChain() {
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
return filterProxy;
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("ROLE_ADMIN").and().httpBasic();
http.authorizeRequests().antMatchers("/admin/login", "/admin/logout", "/admin/denied").permitAll()
.antMatchers("/admin/**").hasRole("ROLE_ADMIN")
.and()
.formLogin()
.loginPage("/admin/login")
.defaultSuccessUrl("/admin/list")
.failureUrl("/admin/denied?failed=true")
.and()
.rememberMe();
http.logout().logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login").deleteCookies("JSESSIONID");
}
}
The XML configuration that I hope to get rid of:
<!-- A REST authentication -->
<http use-expressions="true" pattern="/admin/**">
<intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />
<http-basic entry-point-ref="restAuthenticationEntryPoint" />
<logout />
</http>
<!-- A form based browser authentication -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin/login" access="permitAll" />
<intercept-url pattern="/admin/logout" access="permitAll" />
<intercept-url pattern="/admin/denied" access="permitAll" />
<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<form-login
login-page="/admin/login"
default-target-url="/admin/list"
authentication-failure-url="/admin/denied?failed=true"
always-use-default-target="true" />
<logout logout-success-url="/admin/login" />
<logout delete-cookies="JSESSIONID" />
</http>
<!-- A custom authentication provider on legacy data -->
<authentication-manager>
<authentication-provider ref="customAuthenticationProvider" />
</authentication-manager>
UPDATE:
I added a Configuration directive:
#Configuration
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
and an explicit import directive:
#Import({ SecurityWebApplicationInitializer.class })
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
}
But the exception remained the exact same.
I'm running Spring Security 3.2.4.RELEASE and Spring 3.2.9.RELEASE
If you have any suggestion, it is welcomed.
I removed this bean definition from the security configuration and it seems to have solved the issue
#Bean
public DelegatingFilterProxy springSecurityFilterChain() {
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
return filterProxy;
}

embedded a ldap server with spring-security using java (instead of xml)

I need to embeed a LDAP server with spring for testing purposes. The following code works:
src/main/webapp/WEB-INF/web.xml
[...]
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
[...]
com.example.config.servlet.TestLDAPServerConfiguration
</param-value>
</context-param>
[...]
src/main/java/com/example/config/servlet/TestLDAPServerConfiguration.java
package com.example.config.servlet;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
#Configuration
#ImportResource({"/WEB-INF/test-ldap-server.xml"})
public class TestLDAPServerConfiguration {
}
src/main/webapp/WEB-INF/test-ldap-server.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:s="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<s:ldap-server ldif="classpath:users.ldif" root="dc=nestle,dc=com" port="33389"/>
</beans>
I do need to use AnnotationConfigWebApplicationContext instead of XmlWebApplicationContext. However, here I am using a class TestLDAPServerConfiguration which just imports a test-ldap-server.xml, and this test-ldap-server.xml just declares the ldap-server.
I'd like to remove the test-ldap-server.xml file. How can I do the equivalent of s:ldap-server with java code inside the TestLDAPServerConfiguration class? And where is this documented?
Try something like this;
protected static ApacheDSContainer server;
#BeforeClass
public static void startServer() throws Exception {
server = new ApacheDSContainer( "dc=yourdomain,dc=com", "classpath:test-server.ldif" );
server.setPort( 53389 );
server.afterPropertiesSet();
server.start();
}
#AfterClass
public static void stopServer() throws Exception {
if( server != null ) {
server.stop();
}
}
You can get guides from the spring-security-ldap source code.

Autowiring a bean from one maven module to another maven module within same multi-module maven project

I have a multi module maven project with follwing child module
Tracker
|--Tracker-core
|--Tracker-dao
| |---src/main/resource/spring-dao-config.xml
|
|--Tracker-services
| |---src/main/resource/spring-service-config.xml
|
|--Tracker-web
In Tracker-dao, I have a spring-context.xml in the resource package. this scans for the dao classes and includes other datasource configuration.
spring-dao-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.gits.tracker"></context:component-scan>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/database.properties" />
</bean>
<import resource="classpath:hibernate-config.xml" />
<!-- Declare a datasource that has pooling capabilities -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- An AnnotationSessionFactoryBean for loading Hibernate mappings from
annotated domain classes. -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.gits.tracker.core.entity.Address</value>
<value>com.gits.tracker.core.entity.Company</value>
<value>com.gits.tracker.core.entity.Customer</value>
<value>com.gits.tracker.core.entity.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- <prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</prop> -->
</props>
</property>
</bean>
</beans>
Junit test for the dao layer alone is working perfectly alright.
In the Tracker-service, I have used this Tracker-core as a dependency.
While running the Junit in Tracker-service, it goes error, saying failed to load Application context, failed to find atleast 1 bean matching the name.
spring-service-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- <import resource="classpath:spring-dao-config.xml"/> -->
<context:component-scan base-package="com.gits.tracker.service.services"></context:component-scan>
</beans>
Junit in Tracker-service
Problem is here:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:spring-service-config.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:spring-service-config.xml" })
public class TestUserService extends
AbstractTransactionalJUnit4SpringContextTests {
private static Logger logger;
private static ApplicationContext ctx;
private UserService userService;
#BeforeClass
public static void init() {
logger = Logger.getLogger(User.class);
if (logger.isDebugEnabled()) {
logger.debug("IN DEBUG MODE");
}
}
#Before
public void localInit() {
logger.info("*************EXECUTING LOCALINIT*************");
ctx = new FileSystemXmlApplicationContext(
"src/main/resources/spring-config.xml");
userService = (UserService) ctx.getBean("userServiceImpl");
// userDao.executeQuery("delete from User where id<>3");
logger.info("*************DELETED ALL COMPANY FROM TABLE*************");
logger.info("*************EXITING OUT OF LOCALINIT*************");
}
#AfterClass
public static void stop() {
logger.debug("TEST COMPLETED");
}
private UserServiceImpl loadUserService() {
return (UserServiceImpl) ctx.getBean("userServiceImpl");
}
private UserDTO createTestUserDTO() {
UserDTO dto = new UserDTO("manoj", "manojpass", "true");
return dto;
}
#Test
public void testCreateUser() {
loadUserService();
UserDTO dto = createTestUserDTO();
Long id = userService.createUser(dto);
dto.setId(id);
UserDTO dto_1 = userService.getUserById(id);
org.junit.Assert.assertEquals(dto.toString(), dto_1.toString());
}
#Test
public void findByCriteriaWithAlias() {
loadUserService();
UserDTO dto = createTestUserDTO();
Long id = userService.createUser(dto);
CriteriaWithAlias criteriaWithAlias = new CriteriaWithAlias();
HashMap<String, String> alias = new HashMap<String, String>();
List<Criterion> criterions = new ArrayList<Criterion>();
Criterion criterion0 = Restrictions.eq("username", dto.getUsername());
criterions.add(criterion0);
criteriaWithAlias.setAlias(alias);
criteriaWithAlias.setCriterions(criterions);
List<UserDTO> users = userService
.findByCriteriaWithAlias(criteriaWithAlias);
for (UserDTO user : users) {
org.junit.Assert.assertFalse(user.getPassword().isEmpty());
org.junit.Assert.assertFalse(user.getId().toString().isEmpty());
org.junit.Assert.assertFalse(user.getUsername().isEmpty());
org.junit.Assert.assertFalse(user.getEnabled().isEmpty());
}
}
#Test
public void findByProjection() {
loadUserService();
UserDTO dto = createTestUserDTO();
userService.createUser(dto);
CriteriaWithAlias criteriaWithAlias = new CriteriaWithAlias();
HashMap<String, String> alias = new HashMap<String, String>();
HashMap<String, String> projections = new HashMap<String, String>();
List<Criterion> criterions = new ArrayList<Criterion>();
projections.put("username", "username");
projections.put("enabled", "enabled");
Criterion criterion0 = Restrictions.ne("username", "syed");
Criterion criterion1 = Restrictions.eq("enabled", "true");
criterions.add(criterion0);
criterions.add(criterion1);
criteriaWithAlias.setAlias(alias);
criteriaWithAlias.setCriterions(criterions);
criteriaWithAlias.setProjections(projections);
List<UserDTO> users = userService
.findByCriterionWithProjection(criteriaWithAlias);
for (UserDTO user : users) {
org.junit.Assert.assertNull(user.getPassword());
org.junit.Assert.assertNull(user.getId());
org.junit.Assert.assertFalse(user.getUsername().isEmpty());
org.junit.Assert.assertFalse(user.getEnabled().isEmpty());
}
}
I also tried importing the spring-dao-config of tracker-core in spring-service-config of the tracker-service module. But, that time, it says, spring-dao-config.xml file not found.
Please let me know whats wrong and what I have missed and suggest a solution for this.
I have added the dependency for each module in their own POM.xml and not all together in parent POM.xml
I found solution to my own question. Correct me if I'm wrong.
Its not possible to perform a JUnit test by accessing a config file from another maven module. JUnit is meant for Unit testing only. and not the integration testing.
The dependent maven modules config file will not be available in the classpath for the actual maven module you want to test.
So, what I did was, copied the config file of the dependent maven modules into the classpath of the actual maven module which I need to test. This might not be the correct way of doing it. but, I'm able to perform the JUnit test successfully.
Other way to perform Junit test in such case is to use tools like MOCKITO : https://code.google.com/p/mockito/

Resources