2017-03-07 1 views
1

나는 급한 응용 프로그램을 가지고 있으며, 대부분의 경우 ReferenceError에서 전체 노드 프로세스가 실패하는 상황이 있습니다.winston - 노드 프로세스가 중단되는 오류를 기록하는 방법은 무엇입니까?

노드 충돌을 처리하고 내 콘솔에 나타나는 문제를 로깅하도록 Winston을 설정하는 방법이 있는지 궁금합니다.

ReferenceError: window is not defined

내가 얻을 수있는 방법 윈스턴이를 기록하는 :

예를 들어, 나는 결과 window에 대한 참조에 넣어 충돌이 내 응용 프로그램을 강제 할 수 있습니까? 내 app.js에서

, 나는 윈스턴 위해 설정 다음,하지만 그것은 작동하지 않습니다

const winston = require('winston'); 

const logger = new (winston.Logger)({ 
    transports: [ 
    new (winston.transports.File)({ 
     filename: `results.log`, 
     timestamp: true, 
     level: 'info', 
     json: true, 
     eol: 'n', 
     handleExceptions: true, 
     humanReadableUnhandledException: true 
    }) 
    ], 
    exitOnError: false 
}); 


process.on('uncaughtException', function (error) { 
    console.log('error'); // doesn't log this, 
}); 

누군가가 나를 도울 수 있습니까?

Listening on port 4200 
EXCEPTION: Error in :0:0 caused by: window is not defined 

ORIGINAL EXCEPTION: window is not defined 
ORIGINAL STACKTRACE: 
ReferenceError: window is not defined 
    at AppComponent.ngOnInit (/Users/test/universal/dist/server/server.bundle.js:2135:9) 
    at Wrapper_AppComponent.ngDoCheck (/AppModule/AppComponent/wrapper.ngfactory.js:22:53) 
    at CompiledTemplate.proxyViewClass.View_AppComponent_Host0.detectChangesInternal (/AppModule/AppComponent/host.ngfactory.js:31:26) 
    at CompiledTemplate.proxyViewClass.AppView.detectChanges (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:9354:18) 
    at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:9447:48) 
    at ViewRef_.detectChanges (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:7337:24) 
    at /Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:6588:88 
    at Array.forEach (native) 
    at ApplicationRef_.tick (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:6588:42) 
    at ApplicationRef_._loadComponent (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:6566:18) 
ERROR CONTEXT: 

DebugContext { 
    _view: 
    DebugAppView { 
    clazz: [Function: View_AppComponent_Host0], 
    componentType: 
     RenderComponentType { 
     id: '39', 
     templateUrl: '', 
     slotCount: 0, 
     encapsulation: 2, 
     styles: [], 
     animations: {} }, 
    type: 0, 
    viewUtils: 
     ViewUtils { 
     _renderer: [Object], 
     _nextCompTypeId: 0, 
     sanitizer: DomSanitizerImpl {} }, 
    parentView: null, 
    parentIndex: null, 
    parentElement: null, 
    cdMode: 4, 
    declaredViewContainer: null, 
    viewContainer: null, 
    numberOfChecks: 0, 
    ref: ViewRef_ { _view: [Circular], _originalMode: 2 }, 
    renderer: 
     NodeDomRenderer { 
     _rootRenderer: [Object], 
     componentProto: [Object], 
     _animationDriver: _NoOpAnimationDriver {}, 
     _styles: [], 
     _contentAttr: null, 
     _hostAttr: null, 
     __rootRenderer: [Object] }, 
    _directRenderer: undefined, 
    staticNodeDebugInfos: [ [Object] ], 
    _currentDebugContext: [Circular], 
    context: {}, 
    _hasExternalHostElement: true, 
    _hostInjector: 
     NgModuleInjector { 
     _parent: _NullComponentFactoryResolver {}, 
     _factories: [Object], 
     parent: [Object], 
     bootstrapFactories: [Object], 
     _destroyListeners: [Object], 
     _destroyed: false, 
     _CommonModule_0: CommonModule {}, 
     _ApplicationModule_1: ApplicationModule {}, 
     _NodeModule_2: NodeModule {}, 
     _NodeHttpModule_3: NodeHttpModule {}, 
     _NodeJsonpModule_4: NodeJsonpModule {}, 
     _UniversalModule_5: UniversalModule {}, 
     _InternalFormsSharedModule_6: InternalFormsSharedModule {}, 
     _FormsModule_7: FormsModule {}, 
     _ModalModule_8: ModalModule {}, 
     _CollapseModule_9: CollapseModule {}, 
     _StoreModule_10: StoreModule {}, 
     _EffectsModule_11: EffectsModule {}, 
     _InfiniteScrollModule_12: InfiniteScrollModule {}, 
     _PopoverModule_13: PopoverModule {}, 
     _Token_ROUTER_FORROOT_GUARD_14: 'guarded', 
     _RouterModule_15: RouterModule {}, 
     _CacheService_16: [Object], 
     _AppModule_17: [Object], 
     _ErrorHandler_20: [Object], 
     _ApplicationInitStatus_21: [Object], 
     _TestabilityRegistry_22: [Object], 
     _Testability_23: [Object], 
     _ApplicationRef__24: [Object], 
     _Token_Token__ngrx_store_reducer_62: [Function: reducers], 
     _Token_Token_ngrx_store_reducer_63: [Function: reducers], 
     __Dispatcher_60: [Object], 
     _Reducer_64: [Object], 
     _Token_Token__ngrx_store_initial_state_65: undefined, 
     _Token_Token_ngrx_store_initial_state_66: [Object], 
     _State_67: [Object], 
     _Store_68: [Object], 
     _EffectsSubscription_69: [Object], 
     __ApplicationRef_25: [Object], 
     __UrlSerializer_70: DefaultUrlSerializer {}, 
     __RouterOutletMap_71: [Object], 
     __Token_ORIGIN_URL_44: 'localhost', 
     __Token_REQUEST_URL_45: '/', 
     __Token_appBaseHref_46: '/', 
     __PlatformLocation_47: [Object], 
     __Token_ROUTER_CONFIGURATION_72: {}, 
     __LocationStrategy_73: [Object], 
     __Location_74: [Object], 
     __Compiler_26: [Object], 
     __NgModuleFactoryLoader_75: [Object], 
     __Token_ROUTES_76: [Object], 
     __Router_77: [Object], 
     __NoPreloading_78: NoPreloading {}, 
     __PreloadingStrategy_79: NoPreloading {}, 
     _RouterPreloader_80: [Object], 
     __ResponseOptions_54: [Object], 
     __BrowserXhr_52: [Function: _noop], 
     __XSRFStrategy_51: [Function: _noop], 
     __XHRBackend_55: [Object], 
     __RequestOptions_53: [Object], 
     __Http_56: [Object], 
     __HeaderPromotionsActions_94: HeaderPromotionsActions {}, 
     _CheckoutFormService_98: [Object], 
     instance: [Object], 
     __NodeSharedStylesHost_28: [Object], 
     __Token_DocumentToken_29: [Object], 
     __NodeDomEventsPlugin_30: [Object], 
     __Token_HammerGestureConfig_31: [Object], 
     __Token_EventManagerPlugins_32: [Object], 
     __NodeEventManager_33: [Object], 
     __EventManager_34: [Object], 
     __AnimationDriver_35: _NoOpAnimationDriver {}, 
     __NodeDomRootRenderer_36: [Object], 
     __DomRootRenderer_37: [Object], 
     __RootRenderer_38: [Object], 
     __DomSanitizer_39: DomSanitizerImpl {}, 
     __Sanitizer_40: DomSanitizerImpl {}, 
     __ViewUtils_41: [Object], 
     __AuthService_87: [Object], 
     __ProductActions_93: ProductActions {}, 
     __ActivatedRoute_91: [Object], 
     __IterableDiffers_42: [Object], 
     __KeyValueDiffers_43: [Object] }, 
    _hostProjectableNodes: [], 
    _el_0: 
     { type: 'tag', 
     name: 'app-root', 
     namespace: 'http://www.w3.org/1999/xhtml', 
     attribs: [Object], 
     'x-attribsNamespace': {}, 
     'x-attribsPrefix': {}, 
     children: [Object], 
     parent: [Object], 
     prev: [Object], 
     next: [Object] }, 
    _vc_0: 
     ViewContainer { 
     index: 0, 
     parentIndex: null, 
     parentView: [Circular], 
     nativeElement: [Object] }, 
    compView_0: 
     DebugAppView { 
     clazz: [Function: View_AppComponent0], 
     componentType: [Object], 
     type: 1, 
     viewUtils: [Object], 
     parentView: [Circular], 
     parentIndex: 0, 
     parentElement: [Object], 
     cdMode: 2, 
     declaredViewContainer: null, 
     viewContainer: null, 
     numberOfChecks: 0, 
     ref: [Object], 
     renderer: [Object], 
     _directRenderer: undefined, 
     staticNodeDebugInfos: [Object], 
     _currentDebugContext: [Object], 
     _map_39: [Function], 
     _map_40: [Function], 
     _expr_41: [Object], 
     _map_42: [Function], 
     _expr_43: [Object], 
     _expr_44: [Object], 
     context: [Object], 
     _el_0: [Object], 
     _text_1: [Object], 
     _el_2: [Object], 
     _NgClass_2_3: [Object], 
     _text_3: [Object], 
     _el_4: [Object], 
     _NgClass_4_3: [Object], 
     _text_5: [Object], 
     _text_6: [Object], 
     _text_7: [Object], 
     _anchor_8: [Object], 
     _vc_8: [Object], 
     _TemplateRef_8_5: [Object], 
     _NgIf_8_6: [Object], 
     _text_9: [Object], 
     _el_10: [Object], 
     _NgClass_10_3: [Object], 
     _text_11: [Object], 
     _el_12: [Object], 
     _text_13: [Object], 
     _el_14: [Object], 
     _vc_14: [Object], 
     _RouterOutlet_14_5: [Object], 
     _text_15: [Object], 
     _text_16: [Object], 
     _el_17: [Object], 
     _text_18: [Object], 
     _anchor_19: [Object], 
     _vc_19: [Object], 
     _TemplateRef_19_5: [Object], 
     _NgIf_19_6: [Object], 
     _text_20: [Object], 
     _text_21: [Object], 
     _text_22: [Object], 
     _anchor_23: [Object], 
     _vc_23: [Object], 
     _TemplateRef_23_5: [Object], 
     _NgIf_23_6: [Object], 
     _text_24: [Object], 
     lastRootNode: null, 
     allNodes: [Object], 
     disposables: [Object] }, 
    _AppComponent_0_5: Wrapper_AppComponent { _changed: false, _changes: {}, context: [Object] }, 
    _el_1: 
     { type: 'comment', 
     data: 'template bindings={}', 
     parent: null, 
     prev: null, 
     next: null }, 
    lastRootNode: 
     { type: 'comment', 
     data: 'template bindings={}', 
     parent: null, 
     prev: null, 
     next: null }, 
    allNodes: [ [Object] ], 
    disposables: [ [Function: bound disposeInlineArray], [Function] ] }, 
    _nodeIndex: 0, 
    _tplRow: 0, 
    _tplCol: 0 } 

ReferenceError: window is not defined 
    at AppComponent.ngOnInit (/Users/test/universal/dist/server/server.bundle.js:2135:9) 
    at Wrapper_AppComponent.ngDoCheck (/AppModule/AppComponent/wrapper.ngfactory.js:22:53) 
    at CompiledTemplate.proxyViewClass.View_AppComponent_Host0.detectChangesInternal (/AppModule/AppComponent/host.ngfactory.js:31:26) 
    at CompiledTemplate.proxyViewClass.AppView.detectChanges (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:9354:18) 
    at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:9447:48) 
    at ViewRef_.detectChanges (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:7337:24) 
    at /Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:6588:88 
    at Array.forEach (native) 
    at ApplicationRef_.tick (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:6588:42) 
    at ApplicationRef_._loadComponent (/Users/test/universal/node_modules/@angular/core/bundles/core.umd.js:6566:18) 

여기 (각-보편적 인 사용) 명시 응용 프로그램에서 전체 코드입니다 : 기본적으로

, 나는 내가 목적에 응용 프로그램 충돌을 할 경우 내 콘솔의 등장이 오류를 기록하는 것을 시도하고있다 : 내 원래의 대답은 도움이되지 않았기 때문에

import './polyfills.ts'; 
import './__2.1.1.workaround.ts'; // temporary until 2.1.1 things are patched in Core 
import * as path from 'path'; 
import * as express from 'express'; 
import * as compression from 'compression'; 
import { createEngine } from 'angular2-express-engine'; 
import { enableProdMode } from '@angular/core'; 
import { AppModule } from './app/app.module.node'; 
import { environment } from './environments/environment'; 
import { routes } from './server.routes'; 

const winston = require('winston'); 

const logger = new (winston.Logger)({ 
    transports: [ 
    new (winston.transports.File)({ 
     filename: `results.log`, 
     timestamp: true, 
     level: 'info', 
     json: true, 
     eol: 'n', 
     handleExceptions: true, 
     humanReadableUnhandledException: true 
    }) 
    ], 
    exitOnError: false 
}); 


process.on('uncaughtException', function (error) { 
    console.log('error'); // doesn't log this, 
}); 

// App 

const app = express(); 

const ROOT = path.join(path.resolve(__dirname, '..')); 
const port = process.env.PORT || 4200; 

/** 
* enable prod mode for production environments 
*/ 
if (environment.production) { 
    enableProdMode(); 
} 

/** 
* Express View 
*/ 
app.engine('.html', createEngine({})); 
app.set('views', path.join(ROOT, 'client')); 
app.set('view engine', 'html'); 

/** 
* Enable compression 
*/ 
app.use(compression()); 

/** 
* serve static files 
*/ 
app.use('/', express.static(path.join(ROOT, 'client'), { index: false })); 

const cache = {}; 

function ngApp(req, res) { 
    let baseUrl = '/'; 
    let url = req.originalUrl || '/'; 
    res.setHeader('Cache-Control', 'public, max-age=1000'); 
    if (cache[url]) { 
    res.status(200).send(cache[url]); 
    return; 
    } 
    res.render('index', { 
    req, 
    res, 
    ngModule: AppModule, 
    preboot: { 
     appRoot: ['app-root'], 
     uglify: true, 
     buffer: true 
    }, 
    async: false, 
    baseUrl: baseUrl, 
    requestUrl: req.originalUrl, 
    originUrl: req.hostname 
    }, 
    (err, html) => { 
    cache[url] = html; 
    res.status(200).send(html); 
    }); 
} 

/** 
* use universal for specific routes 
*/ 
app.get('/', ngApp); 
routes.forEach(route => { 
    app.get(`/${route}`, ngApp); 
    app.get(`/${route}/*`, ngApp); 
}); 

/** 
* if you want to use universal for all routes, you can use the '*' wildcard 
*/ 

app.get('*', function (req: any, res: any) { 
    res.setHeader('Content-Type', 'application/json'); 
    const pojo = { status: 404, message: 'No Content' }; 
    const json = JSON.stringify(pojo, null, 2); 
    res.status(404).send(json); 
}); 


app.listen(port,() => { 
    console.log(`Listening on port ${port}`); 
}); 
+0

감사합니다. 나는 그것을 시도했으나 창에 대한 참조로 내 앱을 의도적으로 중단하고 있기 때문에 여전히 작동하지 않습니다. 의도적으로 내 앱을 크래킹하면 콘솔에 이유가 기록 된 것을 볼 수 있습니다. 오류 메시지를 내 기록으로 가져올 수 있습니까? 감사합니다 – user1354934

답변

2

, 난 당신의 코드를 실행하고 제대로 다음과 같은 수정과 캐치되지 않는 예외 로그인 :

process.on('uncaughtException', function (error) { logger.log("error", "qqq") console.log('error'); // just prints the word 'error', });

+0

감사. 업데이트 된 질문을보실 수 있습니까? 기본적으로 내 콘솔에 로그 파일로 표시된 오류를 가져 오려고합니다. 감사합니다. – user1354934

+0

감사합니다. Alon Oz. 내가 언급 한 줄에 넣고이 ErrorHandler도 추가했습니다. 그래서, 그것은 충돌하고 콘솔에 게시 된 그 큰 오류 메시지를 던졌습니다. 그러나 exceptions.log 파일이 생성되지 않았습니다. ( – user1354934

+0

내 대답이 수정되었습니다. 내 노드 6에서 작동합니다. –

관련 문제