Skip to content

Commit b62b29b

Browse files
naseemkullahaustinlparkercartersocha
authored
paymentsservice: structure logs (open-telemetry#520)
Use Pino's [mergingObject](https://github.com/pinojs/pino/blob/master/docs/api.md#mergingobject-object) parameter to add context as JSON rather than in the message parameter, which is now more generic (like an event name). Also factor out logger so it is instantiated once for the whole service and upgrade pino. Also remove unneeded comments. Signed-off-by: Naseem Ullah <[email protected]> Signed-off-by: Naseem Ullah <[email protected]> Co-authored-by: Austin Parker <[email protected]> Co-authored-by: Carter Socha <[email protected]>
1 parent 48f8c32 commit b62b29b

File tree

5 files changed

+22
-1298
lines changed

5 files changed

+22
-1298
lines changed

src/paymentservice/charge.js

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,20 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
// Npm
1615
const {context, propagation, trace} = require('@opentelemetry/api');
1716
const cardValidator = require('simple-card-validator');
18-
const pino = require('pino');
1917
const { v4: uuidv4 } = require('uuid');
2018

21-
// Setup
22-
const logger = pino();
19+
const logger = require('./logger');
2320
const tracer = trace.getTracer('paymentservice');
2421

25-
// Functions
2622
module.exports.charge = request => {
2723
const span = tracer.startSpan('charge');
2824

2925
const { creditCardNumber: number,
3026
creditCardExpirationYear: year,
3127
creditCardExpirationMonth: month
3228
} = request.creditCard;
33-
const { units, nanos, currencyCode } = request.amount;
3429
const currentMonth = new Date().getMonth() + 1;
3530
const currentYear = new Date().getFullYear();
3631
const lastFourDigits = number.substr(-4);
@@ -51,7 +46,7 @@ module.exports.charge = request => {
5146
if (!['visa', 'mastercard'].includes(cardType)) {
5247
throw new Error(`Sorry, we cannot process ${cardType} credit cards. Only VISA or MasterCard is accepted.`);
5348
}
54-
49+
5550
if ((currentYear * 12 + currentMonth) > (year * 12 + month)) {
5651
throw new Error(`The credit card (ending ${lastFourDigits}) expired on ${month}/${year}.`);
5752
}
@@ -66,7 +61,8 @@ module.exports.charge = request => {
6661

6762
span.end();
6863

69-
logger.info(`Transaction ${transactionId}: ${cardType} ending ${lastFourDigits} | Amount: ${units}.${nanos} ${currencyCode}`);
64+
const { units, nanos, currencyCode } = request.amount;
65+
logger.info({transactionId, cardType, lastFourDigits, amount: { units, nanos, currencyCode }}, "Transaction complete.");
7066

7167
return { transactionId }
7268
}

src/paymentservice/index.js

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,14 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
// Npm
1615
const grpc = require('@grpc/grpc-js')
1716
const protoLoader = require('@grpc/proto-loader')
1817
const health = require('grpc-js-health-check')
1918
const opentelemetry = require('@opentelemetry/api')
20-
const pino = require('pino')
2119

22-
// Local
2320
const charge = require('./charge')
21+
const logger = require('./logger')
2422

25-
// Functions
2623
function chargeServiceHandler(call, callback) {
2724
const span = opentelemetry.trace.getActiveSpan();
2825

@@ -31,13 +28,13 @@ function chargeServiceHandler(call, callback) {
3128
span.setAttributes({
3229
'app.payment.amount': parseFloat(`${amount.units}.${amount.nanos}`)
3330
})
34-
logger.info(`PaymentService#Charge invoked by: ${JSON.stringify(call.request)}`)
31+
logger.info({ request: call.request }, "Charge request received.")
3532

3633
const response = charge.charge(call.request)
3734
callback(null, response)
3835

3936
} catch (err) {
40-
logger.warn(err)
37+
logger.warn({ err })
4138

4239
span.recordException(err)
4340
span.setStatus({ code: opentelemetry.SpanStatusCode.ERROR })
@@ -46,14 +43,11 @@ function chargeServiceHandler(call, callback) {
4643
}
4744
}
4845

49-
// Functions
5046
async function closeGracefully(signal) {
5147
server.forceShutdown()
5248
process.kill(process.pid, signal)
5349
}
5450

55-
// Main
56-
const logger = pino()
5751
const hipsterShopPackage = grpc.loadPackageDefinition(protoLoader.loadSync('demo.proto'))
5852
const server = new grpc.Server()
5953

@@ -65,12 +59,12 @@ server.addService(hipsterShopPackage.hipstershop.PaymentService.service, { charg
6559

6660
server.bindAsync(`0.0.0.0:${process.env['PAYMENT_SERVICE_PORT']}`, grpc.ServerCredentials.createInsecure(), (err, port) => {
6761
if (err) {
68-
return logger.error(err)
62+
return logger.error({ err })
6963
}
7064

7165
logger.info(`PaymentService gRPC server started on port ${port}`)
7266
server.start()
73-
}
67+
}
7468
)
7569

7670
process.once('SIGINT', closeGracefully)

src/paymentservice/logger.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const pino = require('pino');
2+
3+
module.exports = pino();

0 commit comments

Comments
 (0)