2017-03-07 33 views
1

我有一個明確的應用程序,並且在某些情況下整個節點進程會失敗,主要是ReferenceError。winston - 如何記錄導致節點進程崩潰的錯誤?

我想知道是否有方法設置Winston來處理節點崩潰,並記錄顯示在我的控制檯中的問題。

例如,我可以強迫我的應用程序通過將在參考window崩潰,導致:

ReferenceError: window is not defined

我怎樣才能得到溫斯頓記錄呢?

在我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

謝謝阿隆奧茲。我把你提到的那一行,並加入了這個ErrorHandler。所以,它會崩潰並拋出我在控制檯中發佈的大錯誤消息。然而,沒有創建一個exceptions.log文件:( – user1354934

+0

修改我的答案,在我的節點上工作6. –