You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
***NOTE: this feature is experimental. The API may change in a backwards
100
+
incompatible way until this is deemed stable. Please provide us feedback so
101
+
that we can better refine this express integration.***
102
+
103
+
We provide a middleware that can be used in an express application. Apart from
104
+
being easy to use, this enables some more powerful features of Stackdriver
105
+
Logging: request bundling.
106
+
107
+
The middleware adds a `bunyan`-style log function to the `request` object. You
108
+
can use this wherever you have access to the `request` object (`req` in the
109
+
sample below). All log entries that are made on behalf of a specific request are
110
+
shown bundled together in the Stackdriver Logging UI.
111
+
112
+
```javascript
113
+
constlb=require('@google-cloud/logging-bunyan');
114
+
115
+
// Import express module and create an http server.
116
+
constexpress=require('express');
117
+
118
+
asyncfunctionstartServer() {
119
+
const {logger, mw} =awaitlb.express.middleware();
120
+
constapp=express();
121
+
122
+
// Install the logging middleware. This ensures that a Bunyan-style `log`
123
+
// function is available on the `request` object. Attach this as one of the
124
+
// earliest middleware to make sure that log function is available in all the
125
+
// subsequent middleware and routes.
126
+
app.use(mw);
127
+
128
+
// Setup an http route and a route handler.
129
+
app.get('/', (req, res) => {
130
+
// `req.log` can be used as a bunyan style log method. All logs generated
131
+
// using `req.log` use the current request context. That is, all logs
132
+
// corresponding to a specific request will be bundled in the Stackdriver
133
+
// UI.
134
+
req.log.info('this is an info log message');
135
+
res.send('hello world');
136
+
});
137
+
138
+
// `logger` can be used as a global logger, one not correlated to any specific
139
+
// request.
140
+
logger.info({port:8080}, 'bonjour');
141
+
142
+
// Start listening on the http server.
143
+
app.listen(8080, () => {
144
+
console.log('http server listening on port 8080');
145
+
});
146
+
}
147
+
148
+
startServer();
149
+
```
150
+
97
151
### Error Reporting
98
152
99
153
Any `Error` objects you log at severity `error` or higher can automatically be picked up by [Stackdriver Error Reporting][error-reporting] if your application is running on Google Cloud Platform. Make sure to add logs to your [uncaught exception][uncaught] and [unhandled rejection][unhandled] handlers if you want to see those errors too.
0 commit comments