Skip to content

Instantly share code, notes, and snippets.

@aldy505
Last active February 2, 2025 01:32
Show Gist options
  • Save aldy505/e8ca93af2c5410d66c895f1c1e364840 to your computer and use it in GitHub Desktop.
Save aldy505/e8ca93af2c5410d66c895f1c1e364840 to your computer and use it in GitHub Desktop.
Very simple Loki client
// This is a very simple Grafana Loki client, should be compatibla with Grafana Loki and Victoria Logs.
// Please bear in mind that because this is "very simple", this is not optimized for production use
// at all, because it doesn't send the logs in batch.
//
// MIT License
//
// Copyright (c) 2025 Reinaldy Rafli <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
const url = "https://your-loki-instance.dev/api/v1/push";
const job = "your job name";
export type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
export function log(level: LogLevel, message: string, extras?: Record<string, string>) {
const currentEpochInNanoseconds = BigInt(Date.now()) * BigInt(1e6);
const body = JSON.stringify({
streams: [
{
stream: {
"job": job,
"level": level,
},
values: [
[currentEpochInNanoseconds.toString(), message, extras ?? {}]
]
}
]
});
const headers = {
"Content-Type": "application/json",
// place an Authorization header here if you need one
};
fetch(url, {
method: "POST",
headers: headers,
body: body,
}).catch(console.error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment