Skip to content

Commit 2767fa7

Browse files
committed
add GeneralLog:
improve code and use AppLogAspect in whole project and remove log in classes
1 parent 46a345e commit 2767fa7

5 files changed

Lines changed: 43 additions & 62 deletions

File tree

src/main/java/ir/bigz/springbootreal/SpringbootRealApplication.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
//TODO add pagination to dao
1212
//TODO add validation
1313
//TODO complex model
14-
//TODO global log
1514

1615
@SpringBootApplication(exclude = {
1716
DataSourceAutoConfiguration.class,

src/main/java/ir/bigz/springbootreal/commons/generallog/AppLogAspect.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package ir.bigz.springbootreal.commons.generallog;
22

3+
import ir.bigz.springbootreal.exception.AppException;
34
import org.aspectj.lang.JoinPoint;
45
import org.aspectj.lang.annotation.AfterReturning;
6+
import org.aspectj.lang.annotation.AfterThrowing;
57
import org.aspectj.lang.annotation.Aspect;
68
import org.aspectj.lang.annotation.Before;
79
import org.slf4j.Logger;
@@ -18,7 +20,7 @@ public class AppLogAspect {
1820
private final Logger LOG = LoggerFactory.getLogger(AppLogAspect.class);
1921

2022
@Before("ir.bigz.springbootreal.commons.generallog.CommonJoinPoint.ControllerExecution()")
21-
public void before(JoinPoint joinPoint){
23+
public void beforeCallControllerMethod(JoinPoint joinPoint){
2224
String methodName = joinPoint.getSignature().getName();
2325
Object[] args = joinPoint.getArgs();
2426
String reduce = Arrays.stream(args).reduce("", (s, s2) -> s + " " + s2).toString();
@@ -28,10 +30,17 @@ public void before(JoinPoint joinPoint){
2830

2931
@AfterReturning(value = "ir.bigz.springbootreal.commons.generallog.CommonJoinPoint.ControllerExecution()",
3032
returning = "obj")
31-
public void afterReturning(JoinPoint joinPoint, Object obj){
33+
public void afterReturningResponseOfControllerMethod(JoinPoint joinPoint, Object obj){
3234
String methodName = joinPoint.getSignature().getName();
3335
Object[] args = joinPoint.getArgs();
3436
String reduce = Arrays.stream(args).reduce("", (s, s2) -> s + " " + s2).toString();
3537
LOG.info("after method: {} | argument: {} | result: {}", methodName, reduce, ((ResponseEntity) obj).getBody());
3638
}
39+
40+
@AfterThrowing(pointcut = "execution(* ir.bigz.springbootreal.service.*.*(..))", throwing = "exception")
41+
public void logAfterThrowException(JoinPoint joinPoint, AppException exception){
42+
String methodName = joinPoint.getSignature().getName();
43+
LOG.info("exception method: {} | errorCode: {} | message: {}",
44+
methodName, exception.getHttpErrorCode(), exception.getDetail());
45+
}
3746
}

src/main/java/ir/bigz/springbootreal/controller/SampleController.java

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22

33
import ir.bigz.springbootreal.service.UserService;
44
import ir.bigz.springbootreal.viewmodel.UserModel;
5-
import org.slf4j.Logger;
6-
import org.slf4j.LoggerFactory;
75
import org.springframework.http.HttpStatus;
86
import org.springframework.http.MediaType;
97
import org.springframework.http.ResponseEntity;
@@ -16,8 +14,6 @@
1614
@RequestMapping("/api/v1")
1715
public class SampleController {
1816

19-
Logger log = LoggerFactory.getLogger(SampleController.class);
20-
2117
final
2218
UserService userService;
2319

@@ -48,15 +44,11 @@ public ResponseEntity<?> updateUser(@RequestBody UserModel userModel, @PathVaria
4844

4945
@PostMapping(path = "/user/delete/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
5046
public ResponseEntity<?> deleteUser(@PathVariable("id") long userId) {
51-
try{
52-
String result = userService.deleteUser(userId);
53-
if(result.equals("Success")){
54-
return ResponseEntity.ok(result);
55-
}
56-
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
57-
}catch (RuntimeException exception){
58-
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
47+
String result = userService.deleteUser(userId);
48+
if(result.equals("Success")){
49+
return ResponseEntity.ok(result);
5950
}
51+
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
6052
}
6153

6254
@GetMapping(path = "/user/all", produces = MediaType.APPLICATION_JSON_VALUE)
Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
package ir.bigz.springbootreal.dal;
22

33
import ir.bigz.springbootreal.dao.User;
4-
import org.slf4j.Logger;
5-
import org.slf4j.LoggerFactory;
64
import org.springframework.stereotype.Component;
75

86
import java.util.ArrayList;
@@ -11,23 +9,17 @@
119
@Component
1210
public class UserRepositoryImpl extends DaoRepositoryImpl<User, Long> implements UserRepository {
1311

14-
final Logger LOG = LoggerFactory.getLogger(UserRepositoryImpl.class);
15-
1612
@Override
1713
public User getUserWithNationalId(String nationalId) {
1814

19-
User u = null;
2015
List<User> resultList = new ArrayList<>();
2116
String query = "select u from User u where u.nationalId like '" + nationalId + "'";
2217

23-
try {
24-
resultList = genericSearch(query);
25-
if(resultList.get(0)!= null){
26-
u = resultList.get(0);
27-
}
28-
}catch (Exception e){
29-
LOG.info("user not found message \n" + e.getMessage());
18+
resultList = genericSearch(query);
19+
20+
if(resultList.size() > 0){
21+
return resultList.get(0);
3022
}
31-
return u;
23+
return null;
3224
}
3325
}

src/main/java/ir/bigz/springbootreal/service/UserServiceImpl.java

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,6 @@
66
import ir.bigz.springbootreal.exception.AppException;
77
import ir.bigz.springbootreal.exception.HttpErrorCode;
88
import ir.bigz.springbootreal.viewmodel.UserModel;
9-
import org.slf4j.Logger;
10-
import org.slf4j.LoggerFactory;
11-
import org.springframework.beans.factory.annotation.Autowired;
129
import org.springframework.cache.annotation.CacheEvict;
1310
import org.springframework.cache.annotation.CachePut;
1411
import org.springframework.cache.annotation.Cacheable;
@@ -17,7 +14,6 @@
1714
import org.springframework.transaction.annotation.Propagation;
1815
import org.springframework.transaction.annotation.Transactional;
1916

20-
import java.util.Collections;
2117
import java.util.List;
2218
import java.util.Objects;
2319
import java.util.Optional;
@@ -27,8 +23,6 @@
2723
@Component
2824
public class UserServiceImpl implements UserService {
2925

30-
final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);
31-
3226
private final UserRepository userRepository;
3327
private final UserMapper userMapper;
3428

@@ -48,26 +42,27 @@ public UserModel getUser(Long userId) {
4842
Optional<User> user = userRepository.find(userId);
4943
return userMapper.userToUserModel(user.get());
5044
}catch (RuntimeException exception){
51-
LOG.info("user not found");
5245
throw AppException.newInstance(
5346
HttpErrorCode.ERR_10702,
54-
String.format("not found user with id : %s", userId)
47+
String.format("user with id, %s not found", userId)
5548
);
5649
}
5750
}
5851

5952
@Override
6053
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
6154
public UserModel addUser(UserModel userModel) {
62-
if(userRepository.getUserWithNationalId(userModel.getNationalId()) == null){
63-
User user = userMapper.userModelToUser(userModel);
64-
return userMapper.userToUserModel(userRepository.insert(user));
65-
}
66-
else{
67-
LOG.info("user has already existed not created");
55+
try {
56+
if(userRepository.getUserWithNationalId(userModel.getNationalId()) == null){
57+
User user = userMapper.userModelToUser(userModel);
58+
return userMapper.userToUserModel(userRepository.insert(user));
59+
}
60+
throw new RuntimeException("user has already exist");
61+
62+
}catch (RuntimeException exception){
6863
throw AppException.newInstance(
6964
HttpErrorCode.ERR_10700,
70-
String.format("user existed with %s nationalId", userModel.getNationalId())
65+
String.format("user has already existed with %s nationalId", userModel.getNationalId())
7166
);
7267
}
7368
}
@@ -76,18 +71,16 @@ public UserModel addUser(UserModel userModel) {
7671
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
7772
@CachePut(value = "userCache", key="#userId", condition = "#userId != null", unless = "#result==null")
7873
public UserModel updateUser(long userId, UserModel userModel) {
79-
Optional<User> user = userRepository.find(userId);
80-
if(user.isPresent()){
74+
try {
75+
Optional<User> user = userRepository.find(userId);
8176
User sourceUser = user.get();
8277
User updateUser = userMapper.userModelToUser(userModel);
8378
mapUserForUpdate(sourceUser, updateUser);
8479
return userMapper.userToUserModel(sourceUser);
85-
}
86-
else{
87-
LOG.info(String.format("user with user id: %s not found", userId));
80+
}catch (RuntimeException exception){
8881
throw AppException.newInstance(
8982
HttpErrorCode.ERR_10703,
90-
String.format("user with user id: %s not found", userId)
83+
String.format("user with userId %s, not found", userId)
9184
);
9285
}
9386
}
@@ -96,19 +89,16 @@ public UserModel updateUser(long userId, UserModel userModel) {
9689
@Override
9790
@CacheEvict(value = "userCache", beforeInvocation = true, key = "#userId")
9891
public String deleteUser(long userId){
99-
10092
try{
101-
if(getUser(userId) != null) {
102-
userRepository.delete(userId);
103-
return "Success";
104-
}
105-
else{
106-
LOG.info("user not found");
107-
return "user not found";
108-
}
109-
}catch (Exception e){
110-
LOG.error("delete user not complete \n" + e.getMessage());
111-
return "failed";
93+
userRepository.find(userId);
94+
userRepository.delete(userId);
95+
return "Success";
96+
97+
}catch (RuntimeException exception){
98+
throw AppException.newInstance(
99+
HttpErrorCode.ERR_10701,
100+
String.format("user with id %s, not found", userId)
101+
);
112102
}
113103
}
114104

@@ -119,7 +109,6 @@ public List<UserModel> getAll() {
119109
Stream<User> allUser = userRepository.getAll();
120110
return allUser.map(userMapper::userToUserModel).collect(Collectors.toList());
121111
}catch (RuntimeException exception){
122-
LOG.info("getAll method has error \n" + exception.getMessage());
123112
throw AppException.newInstance(
124113
HttpErrorCode.ERR_10701,
125114
String.format("getAll method has error: %s", exception.getCause())

0 commit comments

Comments
 (0)