2017-12-01 13 views
1

오늘 약간의 문제로 여전히 오류가 발생합니다. 단지 콘솔 출력을 사용bunyan 로깅 기능을 ES6의 클래스 기능에 바인딩하려면 어떻게합니까?

const tools = new Tools(
    config.region, 
    config.ssl, 
    logger.debug, 
    logger.error 
); 

로거 : 나는에 번연 로거의 기능을 보내 다른 곳에서 수업 시간에

constructor(region, sslEnabled = true, 
    logger =() => {}, errorLogger =() => {}) { 
if (region === undefined || !region) 
    throw new Error("Initialization error: region is required"); 

    this.log =() => {};   // these two lines might be unnecessary 
    this.logError =() => {};  // 
    this.log = logger.bind(this); 
    this.logError = errorLogger.bind(this); 
    this.region = region; 
    this.sslEnabled = sslEnabled; 
} 

: Docs here. 가장 가까운을 내가 가진이있다. 이것은 내가 console.logconsole.error를 전달하면 작동하지만 내가 번연 로거를 통과하면 실패

bunyan usage error: /usr/src/app/src/healthcheck.js:47: 
attempt to log with an unbound log method: `this` is: TTools { 
    log: [Function: bound ], 
    logError: [Function: bound ], 
    region: 'us-west-2', 
    sslEnabled: false } 

이것에 대해 github의 문제가 있지만 정말 명확한 해결 방법을하는하지 않았다. logger.error과 같은 번난 로거 기능을 다른 객체에 전달하려면 어떻게해야합니까? 이것이 가능한가?

답변

1

의이 this 컨텍스트가 손실 때문에 logger.debug 기능을 보낼 때 약 this 다음 그건 불평합니다.

이 문제를 해결하려면 ES6 지방 화살표 함수를 사용하십시오.

const tools = new Tools(
    config.region, 
    config.ssl, 
    x => logger.debug(x), 
    x => logger.error(x) 
); 
0

언 바운드 개체 메서드는 해당 컨텍스트에 바인딩 될 것으로 예상되는 경우 콜백으로 전달하면 안됩니다. console 메서드는 console대부분의 현대 구현에 바인딩되어 있기 때문에 콜백으로 전달할 수 있지만이 문제는 플랫폼 간 코드에서 암시되어서는 안됩니다.

console 메서드는 이미 Node.js에서 console에 바인딩되어 있으므로 추가 조치없이 콜백으로 안전하게 전달할 수 있습니다.

다른 방법, 그것은해야한다 :

const tools = new Tools(
    config.region, 
    config.ssl, 
    logger.debug.bind(logger), 
    logger.error.bind(logger) 
);