Skip to content

Instantly share code, notes, and snippets.

@jeffreyaven
Created February 5, 2023 21:42
Show Gist options
  • Save jeffreyaven/7b218eee7984c81302ac59e15279c72b to your computer and use it in GitHub Desktop.
Save jeffreyaven/7b218eee7984c81302ac59e15279c72b to your computer and use it in GitHub Desktop.
import { Event } from '../helpers/http'; // this is a custom type for the Netlify event object
import fetch from "node-fetch";
// used for `sec-ch-ua-mobile` header value conversion to boolean
function convertToBoolean(value: string): boolean | null {
if (value === '') return null;
if (value === '?0') {
return false;
} else {
return true;
}
}
// main function to send log data to SumoLogic
async function sendToSumo(url: string, logData: any): Promise<void>{
console.info('sending to sumo...');
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(logData)
});
if (!response.ok) {
throw new Error(`Failed to send event to Sumo Logic: ${response.statusText}`);
}
console.info(`SUMO RESPONSE:\n${JSON.stringify(response, null, 2)}`);
}
// this is the function that will be exported and used in your Netlify functions
export const logRequest = async (page: string, jwtId: string, event: Event) => {
try {
const logData = {
jwtId: jwtId,
page: page,
httpMethod: event.httpMethod,
queryStringParameters: event.queryStringParameters || null,
clientConnectionIp: event.headers['x-nf-client-connection-ip'] || null,
country: event.headers['x-country'] || null,
userAgent: event.headers['user-agent'] || null,
referer: event.headers['referer'] || null,
forwardedFor: event.headers['x-forwarded-for'] || null,
forwardedProtocol: event.headers['x-forwarded-proto'] || null,
language: event.headers['x-language'] || null,
origin: event.headers['origin'] || null,
platform: event.headers['sec-ch-ua-platform'] || null,
netlifyRequestId: event.headers['x-nf-request-id'] || null,
isMobile: convertToBoolean(event.headers['sec-ch-ua-mobile'] || ''),
};
console.info(`PAGE REQUEST\n${JSON.stringify(logData, null, 2)}`);
await sendToSumo(`${process.env.SUMO_REQUEST_SOURCE_URL}`, logData);
} catch (error) {
console.error(`logRequest error: ${error}`);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment