Logger Structure args

I am implementing a simple access log in Deno Fresh, but I am not quite sure how to use the standard library Logger. I want to record logs with remote host etc. at the beginning of the sentence like nginx logs, but can I specify the type of log argument? Currently, the implementation is as follows:
log.setup({
handlers: {
accsessLoggerFmt: new log.ConsoleHandler("INFO", {
formatter: (record) => {
const { datetime, levelName, msg, args } = record;

const d = new Date(datetime.getTime() - datetime.getTimezoneOffset() * 6e4);
const logTime = d.toISOString().slice(0, -5) + d.toString().replace(/^.*GMT([-+]\d{2})(\d{2}).*$/, "$1:$2");

let log = `${logTime} ${levelName.padEnd(7)}`;

for (const arg of args) {
log += ` ${arg}`;
}

log += ` ${msg}`;

return log;
}),
},
loggers: {
accessLogger: {
level: "INFO",
handlers: ["accsessLoggerFmt"],
},
},
});

const requestId = ...
const ip = ...

logger.info("Something", requestId, ip);
log.setup({
handlers: {
accsessLoggerFmt: new log.ConsoleHandler("INFO", {
formatter: (record) => {
const { datetime, levelName, msg, args } = record;

const d = new Date(datetime.getTime() - datetime.getTimezoneOffset() * 6e4);
const logTime = d.toISOString().slice(0, -5) + d.toString().replace(/^.*GMT([-+]\d{2})(\d{2}).*$/, "$1:$2");

let log = `${logTime} ${levelName.padEnd(7)}`;

for (const arg of args) {
log += ` ${arg}`;
}

log += ` ${msg}`;

return log;
}),
},
loggers: {
accessLogger: {
level: "INFO",
handlers: ["accsessLoggerFmt"],
},
},
});

const requestId = ...
const ip = ...

logger.info("Something", requestId, ip);
A current implementation requires inserting the remote host or other information to be displayed in the argument each time, which we believe is tedious and prone to errors. I have read the documentation but could not come up with a good solution. Any advice would be appreciated.
DAH
Deno AI Helper21d ago
In the standard Deno logging library, you can indeed customize the log message format to include additional information such as the remote host, similar to how nginx logs are structured. The formatter function you provide to a handler is responsible for constructing the log message format. From the documentation, it's clear that you can use a function-based formatter that takes a LogRecord as an argument and outputs a string. This allows you to define the exact format of your log messages, including any additional arguments you might want to include. Your current implementation is on the right track. You're using a custom formatter to structure your log messages. However, if you find it tedious to include the remote host or other information as arguments each time you log a message, you could consider creating a wrapper function around the logger that includes these details by default. Here's a simplified example of how you might create such a wrapper function:
import * as log from "https://deno.land/std/log/mod.ts";

// Set up your logger as before
log.setup({
// ... your existing setup
});

const accessLogger = log.getLogger("accessLogger");

// Define a wrapper function for logging access information
function logAccess(message, requestId, ip) {
// Here you can include the remote host and other details by default
// and call the logger's info method with the structured message
accessLogger.info(`${ip} ${requestId} ${message}`);
}

// Usage of the wrapper function
const requestId = "abc123";
const ip = "192.168.1.1";

logAccess("User accessed the dashboard", requestId, ip);
import * as log from "https://deno.land/std/log/mod.ts";

// Set up your logger as before
log.setup({
// ... your existing setup
});

const accessLogger = log.getLogger("accessLogger");

// Define a wrapper function for logging access information
function logAccess(message, requestId, ip) {
// Here you can include the remote host and other details by default
// and call the logger's info method with the structured message
accessLogger.info(`${ip} ${requestId} ${message}`);
}

// Usage of the wrapper function
const requestId = "abc123";
const ip = "192.168.1.1";

logAccess("User accessed the dashboard", requestId, ip);
By using a wrapper function like logAccess, you encapsulate the logic for structuring the log message and ensure that the remote host and other details are
DAH
Deno AI Helper21d ago
consistently included in every log entry. This approach reduces the chance of errors and makes your logging code cleaner and easier to maintain. Remember to adjust the wrapper function to include any additional information you need in your logs and to match the structure you desire. 🦕
L
Leokuma20d ago
I find std/logger too difficult to use. I prefer to use simple console.log or something
L
Leokuma20d ago
There's also this module. I've never used it, though: https://github.com/onjara/optic
GitHub
GitHub - onjara/optic: A powerful logging framework for Deno
A powerful logging framework for Deno. Contribute to onjara/optic development by creating an account on GitHub.
A
Arĝentakato20d ago
Thank you. I will try the library you suggested.
More Posts
Add static font files as a fresh pluginHello! I'm creating a component library for Fresh. I'm in the part of setting up the plugin part of Compiling code breaks it (except on Linux)error: [ERR_MODULE_NOT_FOUND] Cannot find module "C:\Users\Eris\AppData\Local\Temp\deno-compile-llm-Interface with unknown amount of keys but all the same typeHow do i create an interface/type that can have unlimited keys but the values are all the same type?How to open a file as blob?Docs for Blob (https://deno.land/api@v1.42.0?s=Blob) say that `File` implements `Blob`. But the docsDeno deploy running my code multiple timesIm hosting a small discord bot on deno deploy but for some reason its firing the events multiple timvalue too large in kv (30kb)I'm getting a value too large error when setting a value in KV (on deploy) even though the value is How to work without a tsconfig.json in VSCode? Getting typescript errors due to React.``` Cannot find name 'Map'. Do you need to change your target library? Try changing the 'lib' compilupdate deno version on Alpineon alpine the version of deno is 1.38.1 https://pkgs.alpinelinux.org/packages?name=deno is there a rDeno blog deployment failureHi all, recently tried to make a new blog post on personal blog, however now the deployment fails (nFresh 1.6 - Deno Deploy - TailwindDeploying my project on deno deploy is not working. Does anyone have the same issue ? I am using taAnalyze dependencies for deno compileIs there a way to analyze the dependencies that is added when running deno compile? My compiled binaHow to install jupyter using deno v1.41.xAccording to the documentation https://docs.deno.com/runtime/manual/tools/jupyter the command should