[express-ipfilter]

- winston daily log 와 같이 사용할 경우 error 라고 해서 uncaughtException 로그에 남지는 않는다.

- npm install express-ipfilter

- 다른 라우터보다 위에 위치해야 합니다.



var ipfilter = require('express-ipfilter').IpFilter;
var IpDeniedError = require('express-ipfilter').IpDeniedError;

// 차단, 허용할 특정 아이피 목록
var ips = ['192.168.0.10', '192.168.0.11'];

// 범위 사용 예시
// 192.168.0.10 ~ 192.168.0.20 안의 범위와 192.168.0.100 차단 or 허용, 
// var ips = [['192.168.0.10', '192.168.0.20'], '192.168.0.100'];

// ips 목록의 ip들만 허용
app.use(ipfilter(ips, {mode: 'allow'}));

// ips 목록의 ip들 차단
// app.use(ipfilter(ips));

app.use(function(err, req, res, _next) {
    //console.log('Error handler', err);
    res.send('Access Denied');                     // page view 'Access Denied'
    if(err instanceof IpDeniedError){
      res.status(401).end();
    }else{
      res.status(err.status || 500).end();
    }
    // res.render('error', {
    //   message: 'You shall not pass',
    //   error: err
    // });
});

..........

app.get('/', function(req, res){
    res.send('allowed IP');
});


'Programming > Node.js' 카테고리의 다른 글

[Node.js] winston Daily 로그 남기기  (0) 2018.05.21

[Node.js Daily 로그 남기기]


- 인터넷에서 검색해서 적용해 봤는데 모듈이 업데이트 되면서 약간 바뀌었는지 filename , datePattern 부분이 제대로 적용이 되지 않았음.

- 나머지 부분은 다른게 없고 filename , datePattern 두 부분만 바뀌었음.


var winston = require('winston'); // 로그 처리 모듈 var winstonDaily = require('winston-daily-rotate-file'); // 로그 일별 처리 모듈

// Date Format 선택
// moment 모듈 설치 필요
function timeStampFormat() {
    return moment().format('YYYY-MM-DD HH:mm:ss.SSS ZZ'); // '2018-01-01 12:12:12.500 +0900'
};

// 그냥 
const tsFormat = () => (new Date()).toLocaleTimeString();      // '2018-01-01'

// 로그 설정
var logger = new (winston.Logger)({
    transports: [
        new (winstonDaily)({                                              // 로그 파일 설정
                name: 'info-file',
                filename: './logs/app_%DATE%.log',                  // 파일 이름 (아래 설정한 날짜 형식이 %DATE% 위치에 들어간다)
                datePattern: 'YYYY-MM-DD',                           // 날짜 형식 (대문자여야 적용된다.)
                colorize: false,
                maxsize: 50000000,                                       // 로그 파일 하나의 용량 제한
                maxFiles: 1000,                                             // 로그 파일 개수 제한
                level: 'info', // info이상 파일 출력                      // 로그 레벨 지정
                showLevel: true,
                json: false,
                timestamp: timeStampFormat                          // 저장될 시간 형식
            }),
        new (winston.transports.Console)({                            // 콘솔 출력
                name: 'debug-console',
                colorize: true,
                level: 'debug', // debug이상 콘솔 출력
                showLevel: true,
                json: false,
                timestamp: timeStampFormat
        })     
    ],
    exceptionHandlers: [                                                  // uncaughtException 발생시 처리
        new (winstonDaily)({
                name: 'exception-file',
                filename: './logs/exception_%DATE%.log',
                datePattern: 'YYYY-MM-DD',
                colorize: false,
                maxsize: 50000000,
                maxFiles: 1000,
                level: 'error',
                showLevel: true,
                json: false,
                timestamp: timeStampFormat
        }),
        new (winston.transports.Console)({
                name: 'exception-console',
                colorize: true,
                level: 'debug',
                showLevel: true,
                json: false,
                timestamp: timeStampFormat
        })     
    ]
});


// 원하는 위치에 로그 삽입
...................
logger.info('Hello, World');
...................


* ./logs/ 위치에
app_2018-05-21.log
exception_2018-05-21.log

형식으로 로그 파일이 생성됨

출력 내용은 아래와 같은 형태.
2018-05-21 15:59:38.764 +0900 - info: Hello, World




'Programming > Node.js' 카테고리의 다른 글

[Node.js] express-ipfilter IP필터 모듈 사용하기  (2) 2018.05.23

+ Recent posts