尝试在应用程序运行时更改摩根的日志记录格式。
该值将在数据库中的某个远程值上更改,我希望morgan的输出会因此而改变。 即。 如果在数据库中值为1,则morgan的格式为'dev',如果值为3,则格式为'combined'
我一直在使用以下行来设置morgan格式:
app.use(morgan(get_verbose())) .use ....其中get_verbose将对应于格式选项。 然而,它没有给出我想要的动态结果 - 它只设置格式一次。
我是否正确地解决了这个问题,或者在运行时仅将摩根限制为1格式?
Attempting to change the format of morgan's logging through the application run time.
The value will change pending on some remote value in a database and I would like morgan's output to change as a result. ie. If in the database the value is 1 morgan's formatting is 'dev', if the value is 3 the formatting is 'combined'
I have the been using the following line to set up morgan with formatting:
app.use(morgan(get_verbose())) .use ....where get_verbose will correspond to the format options. However it is not giving the dynamic results I was wishing for - it's only setting the formatting once.
Am I going about this incorrectly or is morgan limited to only 1 format at run time?
最满意答案
一种方法是创建一个“包装”摩根中间件的中间件功能:
var morganDev = mordan('dev'); var morganCombined = morgan('combined'); app.use(function(req, res, next) { var value = /* get value somehow */ if (value === 1) { morganDev(req, res, next); } else if (value === 3) { morganCombined(req, res, next); } });在前面,您可以为每个日志格式创建一个记录器,但不要将它们中的任何一个附加到应用程序。 在它们的位置,自定义函数读取值并选择哪个记录器应该处理该请求的处理。
安全更新:应该有一个catch-all块来处理value既不是1或3的情况。这个块应该直接调用next() ,否则请求处理将停止并且永远不会向客户端返回响应。
One approach would be to create a middleware function that "wraps" the Morgan middleware:
var morganDev = mordan('dev'); var morganCombined = morgan('combined'); app.use(function(req, res, next) { var value = /* get value somehow */ if (value === 1) { morganDev(req, res, next); } else if (value === 3) { morganCombined(req, res, next); } });Up front, you create one logger for each log format you would like, but don't attach either of them to the app. In their place, a custom function reads the value and chooses which logger should handle the processing for this request.
Safety update: There should be a catch-all else block to handle the case where value is neither 1 or 3. This block should call next() directly, otherwise the request handling will stall and never return a response to the client.
更多推荐
发布评论