Programing

모든 콘솔 메시지에 타임 스탬프 추가

lottogame 2020. 10. 12. 07:04
반응형

모든 콘솔 메시지에 타임 스탬프 추가


전체적으로 많은 console.log () 및 console.error () 문 이 포함 된 완전하고 배포 된 Express 기반 프로젝트가 있습니다. 프로젝트는 forever를 사용하여 실행되며 stdout 및 stderr를 2 개의 개별 파일로 지정합니다.

모두 잘 작동하지만 이제는 오류가 발생한시기를 정확히 알기 위해 타임 스탬프가 누락되었습니다.

내 코드 전체에서 일종의 검색 / 바꾸기를 수행하거나 각 파일에서 콘솔을 재정의하는 일부 npm 모듈을 사용할 수 있지만 꼭 필요한 경우가 아니라면 모든 모델 / 라우트 파일을 건드리고 싶지 않습니다.

모든 호출에 타임 스탬프를 추가 할 수있는 Express 미들웨어와 같은 방법이 있습니까? 아니면 수동으로 추가해야합니까?


그것은 당신이 밝혀 app.js 파일의 상단에있는 콘솔 기능을 무시하고 다른 모든 모듈을 적용합니다. 내 모듈 중 하나가 child_process. 해당 파일의 맨 위에 줄을 복사하면 모두 작동합니다.

기록을 위해 console-stamp ( npm install console-stamp --save) 모듈을 설치하고 app.js 및 childProcess.js 상단에 다음 줄을 추가했습니다.

// add timestamps in front of log messages
require('console-stamp')(console, '[HH:MM:ss.l]');

내 문제는 이제 :date연결 로거의 형식이 다른 콘솔 호출에서 사용하는 형식이 아닌 UTC 형식을 사용한다는 것입니다. 내 자신의 시간 형식을 등록하여 쉽게 수정되었습니다 (부작용으로 다른 dateformat모듈을 console stamp설치하는 대신 함께 제공 되는 모듈이 필요함 ).

// since logger only returns a UTC version of date, I'm defining my own date format - using an internal module from console-stamp
express.logger.format('mydate', function() {
    var df = require('console-stamp/node_modules/dateformat');
    return df(new Date(), 'HH:MM:ss.l');
});
app.use(express.logger('[:mydate] :method :url :status :res[content-length] - :remote-addr - :response-time ms'));

이제 내 로그 파일이 정리 된 것처럼 보입니다 (더 좋게는 구문 분석 가능).

[15:09:47.746] staging server listening on port 3000
[15:09:49.322] connected to database server xxxxx successfully
[15:09:52.743] GET /product 200 - - 127.0.0.1 - 214 ms
[15:09:52.929] GET /stylesheets/bootstrap-cerulean.min.css 304 - - 127.0.0.1 - 8 ms
[15:09:52.935] GET /javascripts/vendor/require.js 304 - - 127.0.0.1 - 3 ms
[15:09:53.085] GET /javascripts/product.js 304 - - 127.0.0.1 - 2 ms
...

다음을 사용하여 파일을 만듭니다.

var log = console.log;

console.log = function(){
  log.apply(console, [Date.now()].concat(arguments));
};

아무것도 기록하기 전에 앱에 필요합니다. console.error필요한 경우 동일한 작업을 수행 하십시오.

이 솔루션 console.log("he%s", "y") // "hey"은 사용하는 경우 변수 삽입 ( )을 파괴 합니다. 필요한 경우 먼저 타임 스탬프를 기록하십시오.

log.call(console, Date.now());
log.apply(console, arguments);

모듈 : "log-timestamp"가 저에게 효과적입니다.

참조 https://www.npmjs.com/package/log-timestamp를

npm install log-timestamp

간편한 사용

console.log('Before log-timestamp');
require('log-timestamp');
console.log('After log-timestamp');

결과

Before log-timestamp
[2012-08-23T20:08:32.000Z] After log-timestamp

log-timestamp 패키지를 사용할 수도 있습니다 . 매우 간단하고 사용자 정의도 가능합니다.


다른 외부 종속성이없는 솔루션을 원하지만 console.log의 전체 기능 (다중 매개 변수, 변수 삽입)을 유지하려면 다음 코드를 사용할 수 있습니다.

var log = console.log;

console.log = function () {
    var first_parameter = arguments[0];
    var other_parameters = Array.prototype.slice.call(arguments, 1);

    function formatConsoleDate (date) {
        var hour = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        var milliseconds = date.getMilliseconds();

        return '[' +
               ((hour < 10) ? '0' + hour: hour) +
               ':' +
               ((minutes < 10) ? '0' + minutes: minutes) +
               ':' +
               ((seconds < 10) ? '0' + seconds: seconds) +
               '.' +
               ('00' + milliseconds).slice(-3) +
               '] ';
    }

    log.apply(console, [formatConsoleDate(new Date()) + first_parameter].concat(other_parameters));
};

formatConsoleDate 함수를 수정하여 원하는 날짜 형식을 지정할 수 있습니다.

This code needs to be written only once on top of your main JavaScript file.

console.log("he%s", "y") will print something like this:

[12:22:55.053] hey

app.use(morgan('[:date[web]] :method :url :status :res[content-length] - :remote-addr - :response-time ms'))

This isn't a direct answer, but have you looked into winston.js? It has a ton more logging options including logging to a json file or database. These always have timestamps by default. Just a thought.


You can use a function util.log from https://nodejs.org/api/util.html.


This implementation is simple, supports original functionality of console.log (passing a single object, and variable substitution), doesn't use external modules and prints everything in a single call to console.log:

var origlog = console.log;

console.log = function( obj, ...placeholders ){
    if ( typeof obj === 'string' )
        placeholders.unshift( Date.now() + " " + obj );
    else
    {
        // This handles console.log( object )
        placeholders.unshift( obj );
        placeholders.unshift( Date.now() + " %j" );
    }

    origlog.apply( this, placeholders );
};

Use event listener like this,

process.on('error', function() { 
   console.log('Error Occurred.');

   var d = Date(Date.now()).toString();
   console.log.call(console, d); // Wed Aug 07 2019 23:40:07 GMT+0100 (GMT+01:00)
});

happy coding :)

참고URL : https://stackoverflow.com/questions/18814221/adding-timestamps-to-all-console-messages

반응형