Okay, so today I wanted to mess around with Winston and see what it could do for logging in a * app. I’d heard good things, and honestly, my usual `*()` approach was getting messy. I decided to build a super simple “football” score tracker – just to have something to log, you know?
Getting Started
First, I spun up a new project folder and did the usual `npm init -y` to get a `*` file going. Then I installed Winston: `npm install winston`. Easy peasy.
Setting up Winston
Next, I created a new file, `*`. Inside, I brought in Winston:
const winston = require('winston');
Then, I configured a basic logger. I wanted it to log to the console AND to a file. Here’s what I ended up with:
const logger = *({
level: 'info',
format: *(
transports: [
new *(),
new *({ filename: '*' })
I set the `level` to ‘info’, so it would catch ‘info’, ‘warn’, and ‘error’ messages. The `format` part is cool – I used `combine` to add timestamps and output everything as JSON. Makes it easier to read, especially in the log file. Then, the `transports` – one for the console, and one to write to a file named `*`.
The “Football” App
Now for the “app” itself – `*`. It’s super basic, just a couple of functions to simulate scoring:
const logger = require('./logger');
function teamScores(teamName, points) {
*(`Team ${teamName} scores ${points} points!`);
// ... maybe update a score variable or something, later...
function gameEnds(team1, team2, score1, score2)
if(score1 > score2)
*(`${team1} win ! Final Score: ${team1} ${score1}, ${team2} ${score2}`);
else if(score1 < score2)
*(`${team2} win ! Final Score: ${team1} ${score1}, ${team2} ${score2}`);
else
*(`Game ended in Draw ! Final Score: ${team1} ${score1}, ${team2} ${score2}`);
teamScores("Rams", 7);
teamScores("Eagles", 3);
teamScores("Rams", 3);
teamScores("Eagles", 7);
gameEnds("Rams","Eagles",10,10);
See? Instead of `*()`, I’m using `*()`. That’s it! When I run this (`node *`), I get nice, timestamped messages in my console, AND they’re all neatly stored in `*`.
Trying out different levels
I changed the `gameEnds` function messages in `*` so it call `*()` when game ended in draw. And I got a nice warning-level log in my `*`, separate from the info-level stuff:
{"level":"warn","message":"Game ended in Draw ! Final Score: Rams 10, Eagles 10","timestamp":"2024-11-02T04:27:21.397Z"}
What I learned
Winston is super easy to set up. Like, ridiculously easy.
The formatting options are great. JSON output is a lifesaver.
Logging to multiple places (console + file) is trivial.
I should really add error handling and use `*()`. I definitely didn’t do that yet…
Overall, a good first experiment! I’m definitely going to use Winston in my future projects. It’s way better than a bunch of `*` statements scattered everywhere. Next, I might play around with custom log levels and maybe even send logs to a remote server… we’ll see!