我有一个明确的应用程序,并且在某些情况下整个节点进程将失败,主要是在ReferenceError上。
我想知道是否有办法设置Winston来处理节点崩溃,并记录显示在我的控制台中的问题。
例如,我可以通过引用window
来强制我的应用程序崩溃,从而导致:
ReferenceError: window is not defined
如何让winston记录下来?
在我的app.js中,我为Winston设置了以下内容,但它不起作用:
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)
以下是快递应用程序的完整代码(使用angular-universal):
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 :(得分:2)
由于我的原始答案没有帮助,我运行了您的代码并通过以下修改正确记录了未捕获的异常:
process.on('uncaughtException', function (error) {
logger.log("error", "qqq")
console.log('error'); // just prints the word 'error',
});