Comments (2)
NVM I did this and it's working
import { NextRequest } from "next/server";
import baseLogger from "./baseLogger";
import { posthogCookieName } from "./constants";
const getLogger = (name: string, req?: NextRequest) => {
if (typeof window !== "undefined") {
// Browser (client)
// Get cookie from browser
const cookies = document.cookie;
const cookieKeyValues = cookies.split(";").map((cookie) => cookie.trim().split("="));
const posthog = cookieKeyValues.find(([key]) => key === posthogCookieName);
let correlationId = null;
if (posthog) {
try {
const posthookCookieValue = posthog[1];
const value = JSON.parse(decodeURIComponent(posthookCookieValue));
correlationId = value?.distinct_id;
} catch (error) {
console.error("Error parsing posthog cookie", error);
}
}
const windowLocation = window.location;
const windowQueryParams = new URLSearchParams(windowLocation.search)
const queryParamsObj = Object.fromEntries(windowQueryParams.entries());
return baseLogger.child({
name,
from: "browser",
correlationId,
window: {
location: windowLocation.href,
search: queryParamsObj,
}
});
} else {
// Server Side
// Check if edge runtime
// @ts-ignore
const isEdgeRuntime = typeof EdgeRuntime !== 'undefined';
if (isEdgeRuntime) {
if (!req) {
throw new Error('Request object is required in edge runtime');
}
const requestId = req?.headers.get("x-vercel-id");
let headersJson = Object.fromEntries(req.headers.entries()) || {};
// All headers except cookie
delete headersJson['cookie']
const posthog = req.cookies.get(posthogCookieName)
const value = JSON.parse(posthog?.value || '{}');
const distinctId = value?.distinct_id
const nextUrl = req.nextUrl;
const logger = baseLogger.child({
requestId,
correlationId: distinctId,
url: nextUrl.href,
method: req.method,
headers: headersJson,
cookies: req.cookies.getAll(),
geo: req.geo,
from: "edge",
name,
});
return logger;
} else {
const {
cookies,
headers,
} = require("next/headers");
const posthog = cookies().get(posthogCookieName);
const value = JSON.parse(posthog?.value || "{}");
const distinctId = value?.distinct_id;
const requestId = headers().get("x-vercel-id");
return baseLogger.child({
name,
from: "server",
correlationId: distinctId,
requestId,
});
}
}
}
export default getLogger;
In middleware:
const logger = getLogger('middleware', request)
Client side:
const logger = getLogger('src/app/(website)/_components/Navbar.tsx');
from pino.
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
from pino.
Related Issues (20)
- create a function to capture full log object HOT 1
- consider using toad-cache HOT 2
- Filtering of the content using transformations in the pipeline for multiple transports HOT 1
- [question] How do I create dynamic customized logfile names? HOT 3
- Inclusive language suggestion: rename default branch to "main" across Pino's repos HOT 3
- Bundling to `ESM` using `vite` HOT 1
- ESLint: Unsafe call of an `any` typed value.(@typescript-eslint/no-unsafe-call) HOT 2
- Applying regex to redact keys or value HOT 3
- Accessing log level label from transport HOT 6
- Verifying logs from unit tests (again!) HOT 6
- `pino.transport.pipeline` may have lost logs HOT 10
- Docs: Pino Logging with Grafana Promtail/Loki HOT 3
- [Question] Same logger for both node and browser HOT 3
- Transport is not being waited for in lambda HOT 3
- pino assign takes only http context HOT 1
- Import error when using worker with pkg HOT 1
- Release, Tag and Changelog Entry needed for v9 Release HOT 1
- v9 release doesn't list breaking changes HOT 2
- Promise catch directly calling error log results in "Cannot read properties of undefined" exception HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pino.