### Install @rbxts/log Package Source: https://github.com/roblox-aurora/rbx-log/blob/master/README.md Install the @rbxts/log package using npm. ```bash npm i @rbxts/log ``` -------------------------------- ### Set Up Custom Callback Sink for Analytics Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Demonstrates setting up a custom callback sink to process log events, with an example of accessing structured event data and properties. ```typescript import Log, { Logger, LogLevel, LogEvent } from "@rbxts/log"; // Custom callback sink for analytics Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput()) // Also write to RobloxOutput .WriteToCallback((message: LogEvent) => { // Access structured event data print("Level:", message.Level); print("Template:", message.Template); print("Timestamp:", message.Timestamp); print("Source:", message.SourceContext); // Access captured properties by name if (message.PlayerName !== undefined) { print("Player:", message.PlayerName); } // Send to external service // AnalyticsService.TrackEvent(message); }) .WriteToCallback((message) => { // Multiple callbacks supported - log to file system // FileSystem.AppendLog(message); }, (sink) => { // Configure callback sink with minimum log level sink.SetMinLogLevel(LogLevel.Warning); }) .Create() ); Log.Info("Player {PlayerName} joined the game", "TestPlayer"); // Callback receives: { Level: 2, Template: "Player {PlayerName} joined...", PlayerName: "TestPlayer", ... } ``` -------------------------------- ### Basic Logger Configuration and Usage Source: https://github.com/roblox-aurora/rbx-log/blob/master/README.md Configure the logger to write to Roblox Output and log an informational message. Ensure this setup is done separately for server and client environments. ```typescript import Log, { Logger } from "@rbxts/log"; Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput()) // WriteTo takes a sink and writes to it .Create() // Creates the logger from the configuration ); Log.Info("Hello, Log!"); ``` -------------------------------- ### Configure RobloxOutput Sink with Prefix Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Sets up the RobloxOutput sink with a custom prefix, useful for distinguishing logs in multi-system games. ```typescript // With prefix for multi-system games Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput({ Prefix: "Combat" })) .Create() ); Log.Info("Damage dealt to {Target}", "Enemy"); // Output: [Combat] [INF] Damage dealt to Enemy ``` -------------------------------- ### Use Message Templates with Named Parameters Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Demonstrates logging messages using the Message Templates specification with named parameters. Use '@' to serialize objects and '$' to force toString conversion. ```typescript import Log, { Logger } from "@rbxts/log"; Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput()) .Create() ); // Simple named parameters const playerName = "Vorlias"; const score = 1500; Log.Info("Player {PlayerName} achieved score {Score}", playerName, score); // Output: [INF] Player Vorlias achieved score 1500 // Serialize objects with @ prefix - converts to JSON structure const position = new Vector2(25, 134); const startPoint = new Vector2(0, 0); const distance = position.sub(startPoint).Magnitude; Log.Info("Walked to {@Position}, travelling {Distance} studs", position, distance); // Output: [INF] Walked to {"X": 25, "Y": 134}, travelling 136.32 studs // Force toString with $ prefix Log.Info("Instance path: {$Instance}", game.Workspace); // Output: [INF] Instance path: Workspace // Arrays and objects Log.Info("Data: {Name} {@Array} {@Object}", "Test", [1, 2, 3], { health: 100, speed: 16 }); // Output: [INF] Data: Test [1,2,3] {"health":100,"speed":16} ``` -------------------------------- ### Configure and Use a Standalone Logger Instance Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Create a standalone logger with custom configurations like minimum log level and enriched properties. Use this logger for specific modules or features that require independent logging settings. ```typescript import Log, { Logger, LogLevel } from "@rbxts/log"; // Create and configure a standalone logger const logger = Logger.configure() .SetMinLogLevel(LogLevel.Debugging) .EnrichWithProperty("Module", "Standalone") .WriteTo(Log.RobloxOutput()) .Create(); // All log level methods available logger.Verbose("Very detailed trace info"); logger.Debug("Debugging information"); logger.Info("Normal info message with {Data}", "value"); logger.Warn("Warning about {Issue}", "potential problem"); logger.Error("Error occurred: {ErrorMessage}", "something failed"); logger.Fatal("Fatal error - cannot continue"); // Write with explicit log level logger.Write(LogLevel.Information, "Custom level message {Value}", 42); // Get current log level const currentLevel = logger.GetLevel(); print("Current level:", currentLevel); // LogLevel.Debugging (1) // Change log level at runtime logger.SetMinLogLevel(LogLevel.Warning); // Copy logger configuration to create derived logger const derivedConfig = logger.Copy(); const derivedLogger = derivedConfig .EnrichWithProperty("Derived", true) .SetMinLogLevel(LogLevel.Error) .Create(); derivedLogger.Error("This derived logger has additional properties"); // Inherits "Module" property, adds "Derived" property ``` -------------------------------- ### Configure Rbxts Log with Roblox Output Sink Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Sets up the global logger to use the Roblox console for output. This is a basic configuration for simple use cases. ```typescript import Log, { Logger, LogLevel } from "@rbxts/log"; // Basic configuration with Roblox output sink Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput()) .Create() ); // Advanced configuration with multiple sinks, enrichers, and log level Log.SetLogger( Logger.configure() .SetMinLogLevel(LogLevel.Debugging) .EnrichWithProperty("Version", "1.0.0") .EnrichWithProperty("Environment", "Production") .WriteTo(Log.RobloxOutput({ TagFormat: "full", Prefix: "MyGame" })) .WriteToCallback((message) => { // Send to external analytics service print(`Custom sink received: ${message.Template}`); }) .Create() ); Log.Info("Application started with version {Version}", "1.0.0"); // Output: [MyGame] [INFO] Application started with version 1.0.0 ``` -------------------------------- ### Property-Based Child Loggers with ForProperty/ForProperties Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Create child loggers enriched with specific properties using `ForProperty` or `ForProperties`. This is ideal for tracking sessions, users, or other contextual data. Properties can be chained for request-scoped logging. ```typescript import Log, { Logger } from "@rbxts/log"; Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput()) .WriteToCallback((msg) => { print("UserId:", msg.UserId); print("SessionId:", msg.SessionId); }) .Create() ); // Single property enrichment const userLogger = Log.ForProperty("UserId", 12345); userLogger.Info("User performed action"); // All messages include UserId: 12345 // Multiple properties enrichment const sessionLogger = Log.ForProperties({ UserId: 12345, SessionId: "abc-123-xyz", Platform: "Desktop", }); sessionLogger.Info("Session started"); // All messages include UserId, SessionId, Platform // Chain for request-scoped logging function handleRequest(userId: number, requestId: string) { const requestLogger = Log.ForProperties({ UserId: userId, RequestId: requestId, }); requestLogger.Info("Request started"); // Perform operations... requestLogger.Info("Request completed with status {Status}", "success"); } handleRequest(42, "req-001"); // Both log entries include UserId: 42, RequestId: "req-001" ``` -------------------------------- ### Configure Flamework DI Logger Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Register a contextual logger with Flamework's dependency injection system. Ensure this is done in your main server or client entry point. ```typescript import Log, { Logger } from "@rbxts/log"; import { Service, Modding } from "@flamework/core"; // Register Logger as a dependency (in index.server.ts / index.client.ts) Modding.registerDependency((ctor) => { // Automatically creates a logger with SourceContext set to the requesting class return Log.ForContext(ctor); }); // Configure the global logger Log.SetLogger( Logger.configure() .EnrichWithProperty("Version", PKG_VERSION) .WriteTo(Log.RobloxOutput()) .Create() ); // Services automatically receive contextual loggers via constructor injection @Service() export class InventoryService { public constructor(private readonly logger: Logger) {} public addItem(playerId: number, itemId: string) { this.logger.Info("Adding item {ItemId} to player {PlayerId}", itemId, playerId); // SourceContext automatically set to "InventoryService" } } @Service() export class CombatService { public constructor(private readonly logger: Logger) {} public dealDamage(targetId: number, damage: number) { this.logger.Info("Dealing {Damage} damage to {TargetId}", damage, targetId); // SourceContext automatically set to "CombatService" } } ``` -------------------------------- ### Configure RobloxOutput Sink with Full Tag Format Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Configures the logger to use the RobloxOutput sink with a 'full' tag format, displaying the full log level names. ```typescript // Full tag format: VERBOSE, DEBUG, INFO, WARNING, ERROR, FATAL Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput({ TagFormat: "full" })) .Create() ); Log.Info("Full format message"); // Output: [INFO] Full format message ``` -------------------------------- ### Configure RobloxOutput Sink with Short Tag Format Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Sets the logger to use the RobloxOutput sink with a 'short' tag format. This is the default format. ```typescript import Log, { Logger, LogLevel } from "@rbxts/log"; // Short tag format (default): VRB, DBG, INF, WRN, ERR, FTL Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput({ TagFormat: "short" })) .Create() ); Log.Info("Short format message"); // Output: [INF] Short format message ``` -------------------------------- ### Context-Based Logging with ForContext Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Use `ForContext` to create child loggers with the `SourceContext` property automatically set. This is useful for identifying the origin of log messages from classes, services, or modules. You can also configure minimum log levels and enrich logs with custom properties. ```typescript import Log, { Logger, LogLevel } from "@rbxts/log"; Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput()) .WriteToCallback((msg) => print("SourceContext:", msg.SourceContext)) .Create() ); // ForContext with class constructor class PlayerService { private logger = Log.ForContext(PlayerService); public onPlayerJoin(player: Player) { this.logger.Info("Player {PlayerName} joined", player.Name); // SourceContext: "PlayerService" } public onPlayerLeave(player: Player) { this.logger.Info("Player {PlayerName} left", player.Name); // SourceContext: "PlayerService" } } // ForContext with Instance const myScript = script; const scriptLogger = Log.ForContext(myScript); scriptLogger.Info("Script initialized"); // SourceContext: "ServerScriptService.MyScript" (full path) // ForContext with custom configuration class CombatService { private logger = Log.ForContext(CombatService, (config) => { config.SetMinLogLevel(LogLevel.Warning); config.EnrichWithProperty("System", "Combat"); }); public dealDamage(target: string, amount: number) { this.logger.Warn("Damage dealt: {Amount} to {Target}", amount, target); // SourceContext: "CombatService", System: "Combat" } } ``` -------------------------------- ### Enrich Log Events with Static Properties Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Adds static properties like 'Version' and 'Environment' to all log events using EnrichWithProperty and EnrichWithProperties. ```typescript import Log, { Logger, LogLevel } from "@rbxts/log"; // Add static properties to all log events Log.SetLogger( Logger.configure() .EnrichWithProperty("Version", "2.1.0") .EnrichWithProperty("Environment", "Production") .EnrichWithProperties({ ServerRegion: "US-East", BuildNumber: 1234, }) .WriteTo(Log.RobloxOutput()) .WriteToCallback((message) => { // Every message now contains Version, Environment, ServerRegion, BuildNumber print("Version:", message.Version); // "2.1.0" print("Region:", message.ServerRegion); // "US-East" }) .Create() ); Log.Info("Server started"); // Event data includes: { Version: "2.1.0", Environment: "Production", ServerRegion: "US-East", BuildNumber: 1234, ... } ``` -------------------------------- ### Service Logging with Flamework ForContext Source: https://github.com/roblox-aurora/rbx-log/blob/master/README.md Use `Log.ForContext` to create a logger specific to a service class within Flamework. ```typescript @Service() export class MyService { public readonly logger = Log.ForContext(MyService); } ``` -------------------------------- ### Script and Function Context Logging Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Utilize `ForScript` to automatically capture the calling script as context, or `ForFunction` to capture function metadata including name, line number, and source file for detailed debugging. Anonymous functions are logged as '(anonymous)'. ```typescript import Log, { Logger } from "@rbxts/log"; Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput()) .WriteToCallback((msg) => { print("Context:", msg.SourceContext); print("Kind:", msg.SourceKind); if (msg.SourceLine) print("Line:", msg.SourceLine); if (msg.SourceFile) print("File:", msg.SourceFile); }) .Create() ); // ForScript - captures the calling script automatically const scriptLogger = Log.ForScript(); scriptLogger.Info("Logging from this script"); // SourceContext: "ServerScriptService.MyScript" // SourceKind: "Script" // ForScript with additional configuration const configuredScriptLogger = Log.ForScript((config) => { config.EnrichWithProperty("Module", "Inventory"); }); configuredScriptLogger.Info("Inventory system loaded"); // ForFunction - captures function name, line, and source file function processPayment(amount: number) { // Function body } const paymentLogger = Log.ForFunction(processPayment); paymentLogger.Info("Processing payment of {Amount}", 100); // SourceContext: "function 'processPayment'" // SourceKind: "Function" // SourceLine: 25 // SourceFile: "ServerScriptService.PaymentService" // Anonymous functions show as "(anonymous)" const anonLogger = Log.ForFunction(() => {}); anonLogger.Info("From anonymous function"); // SourceContext: "function '(anonymous)'" ``` -------------------------------- ### Structured Logging with Message Templates Source: https://github.com/roblox-aurora/rbx-log/blob/master/README.md Log structured event data using message templates. The '@' operator serializes objects, while named parameters are formatted into the log message. ```typescript const startPoint = new Vector2(0, 0) const position = new Vector2(25, 134); const distance = position.sub(startPoint).Magnitude; Log.Info("Walked to {@Position}, travelling a distance of {Distance}", position, distance); ``` -------------------------------- ### Understand and Utilize LogEvent Structure Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Examine the structure of a LogEvent, which includes level, timestamp, template, source context, and all enriched properties. This is useful for custom sinks like callbacks to process and act upon log data. ```typescript import Log, { Logger, LogLevel, LogEvent } from "@rbxts/log"; // LogEvent interface structure: // { // Level: LogLevel; // Timestamp: string; // Template: string; // SourceContext?: string; // [name: string]: unknown; // } Log.SetLogger( Logger.configure() .EnrichWithProperty("AppVersion", "1.0.0") .WriteTo(Log.RobloxOutput()) .WriteToCallback((event: LogEvent) => { // Core event properties print("Level:", LogLevel[event.Level]); // "Information", "Warning", etc. print("Timestamp:", event.Timestamp); // "2024-01-15T10:30:00.000Z" print("Template:", event.Template); // "Player {Name} scored {Points}" print("Source:", event.SourceContext); // "GameService" or undefined // Enriched properties print("Version:", event.AppVersion); // "1.0.0" // Captured template properties print("Name:", event.Name); // "TestPlayer" print("Points:", event.Points); // 100 // Check log level for conditional handling if (event.Level >= LogLevel.Error) { // Send errors to external monitoring service } }) .Create() ); const gameLogger = Log.ForContext("GameService"); gameLogger.Info("Player {Name} scored {Points}", "TestPlayer", 100); ``` -------------------------------- ### Parse and Render Message Templates Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Use MessageTemplateParser to convert template strings into tokens and PlainTextMessageTemplateRenderer to render them with provided values. Supports destructuring and dynamic rendering. ```typescript import { MessageTemplateParser, PlainTextMessageTemplateRenderer } from "@rbxts/message-templates"; // Parse a template into tokens const tokens = MessageTemplateParser.GetTokens("Hello, {Name}! Your score is {Score}."); // Tokens array contains: // - TextToken: { kind: 0, text: "Hello, " } // - PropertyToken: { kind: 1, propertyName: "Name", destructureMode: 0 } // - TextToken: { kind: 0, text: "! Your score is " } // - PropertyToken: { kind: 1, propertyName: "Score", destructureMode: 0 } // - TextToken: { kind: 0, text: "." } // Render template with values const renderer = new PlainTextMessageTemplateRenderer(tokens); const output = renderer.Render({ Name: "Vorlias", Score: 1500, }); print(output); // "Hello, Vorlias! Your score is 1500." // Parse template with destructure modes const complexTokens = MessageTemplateParser.GetTokens("Player {@Data} moved to {$Position}"); // PropertyToken for Data: destructureMode = Destructure (serializes object) // PropertyToken for Position: destructureMode = ToString (calls tostring) // Dynamic template rendering const hour = DateTime.fromUnixTimestamp(os.time()).ToLocalTime().Hour; const greetingTokens = MessageTemplateParser.GetTokens("Good {TimeOfDay}, {Name}!"); const greetingRenderer = new PlainTextMessageTemplateRenderer(greetingTokens); print(greetingRenderer.Render({ Name: "Player", TimeOfDay: hour < 12 ? "morning" : hour < 18 ? "afternoon" : "evening", })); ``` -------------------------------- ### Enrich Logging Events with Properties Source: https://github.com/roblox-aurora/rbx-log/blob/master/README.md Add custom properties to all logging events using `EnrichWithProperty`. This is useful for including application version or other contextual data. ```typescript Log.SetLogger( Logger.configure() // ... .EnrichWithProperty("Version", PKG_VERSION) // Will add "Version" to the event data // ... .Create() ); ``` -------------------------------- ### Configure RobloxOutput Sink to Treat Errors as Exceptions Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Configures the RobloxOutput sink to treat 'Error' and 'Fatal' log levels as exceptions, preventing them from being printed to the console and enabling a throw pattern. ```typescript // Treat errors as exceptions (for throw pattern) Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput({ ErrorsTreatedAsExceptions: true })) .Create() ); // Error/Fatal won't print to console, allowing throw pattern throw Log.Fatal("Invalid input '{Input}' provided", "badValue"); ``` -------------------------------- ### Flamework Dependency Injection for Logger Source: https://github.com/roblox-aurora/rbx-log/blob/master/README.md Register the `Logger` with Flamework's dependency resolution system to inject it directly into service constructors. ```typescript import Log, { Logger } from "@rbxts/log"; Modding.registerDependency((ctor) => { return Log.ForContext(ctor); // will register this under the given DI class }); ``` -------------------------------- ### Flamework Service with Injected Logger Source: https://github.com/roblox-aurora/rbx-log/blob/master/README.md A Flamework service that receives the `Logger` instance via dependency injection in its constructor. ```typescript @Service() export class MyService { public constructor(private readonly logger: Logger) {} } ``` -------------------------------- ### Configure Log Level Filtering Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Configures the logger to only output messages at or above a specified log level. Messages below this level are ignored. The log level can also be changed at runtime. ```typescript import Log, { Logger, LogLevel } from "@rbxts/log"; // Configure with minimum level - only Warning and above will be logged Log.SetLogger( Logger.configure() .SetMinLogLevel(LogLevel.Warning) .WriteTo(Log.RobloxOutput()) .Create() ); // These will NOT be logged (below Warning level) Log.Verbose("Detailed trace information"); Log.Debug("Debug information for development"); Log.Info("Normal operational message"); // These WILL be logged (Warning level and above) Log.Warn("Something unexpected happened with {Resource}", "database"); Log.Error("Operation failed for user {UserId}", 12345); Log.Fatal("Critical system failure - shutting down"); // Change log level at runtime Log.SetMinLogLevel(LogLevel.Debugging); Log.Debug("Now this will be logged"); ``` -------------------------------- ### Serialize Roblox Types for Logging Source: https://context7.com/roblox-aurora/rbx-log/llms.txt rbx-log automatically serializes common Roblox types like Vector3, Color3, UDim2, DateTime, Instances, EnumItems, and NumberRanges into JSON-compatible structures. ```typescript import Log, { Logger } from "@rbxts/log"; Log.SetLogger( Logger.configure() .WriteTo(Log.RobloxOutput()) .WriteToCallback((msg) => { // Access serialized values print("Position data:", msg.Position); }) .Create() ); // Vector3 serialization const pos = new Vector3(10, 25, 30); Log.Info("Player at {@Position}", pos); // Position serialized as: { X: 10, Y: 25, Z: 30 } // Vector2 serialization const screenPos = new Vector2(100, 200); Log.Info("UI element at {@ScreenPosition}", screenPos); // ScreenPosition serialized as: { X: 100, Y: 200 } // Color3 serialization const color = new Color3(1, 0.5, 0); Log.Info("Particle color {@Color}", color); // Color serialized as: { R: 1, G: 0.5, B: 0 } // UDim2 serialization const size = new UDim2(0.5, 10, 0.5, 20); Log.Info("Frame size {@Size}", size); // Size serialized as: { X: { Scale: 0.5, Offset: 10 }, Y: { Scale: 0.5, Offset: 20 } } // DateTime serialization const timestamp = DateTime.now(); Log.Info("Event at {@Timestamp}", timestamp); // Timestamp serialized as ISO date string: "2024-01-15T10:30:00Z" // Instance serialization (uses GetFullName) const part = game.Workspace.FindFirstChild("SpawnPoint"); Log.Info("Spawning at {@SpawnLocation}", part); // SpawnLocation serialized as: "Workspace.SpawnPoint" // EnumItem serialization Log.Info("Material is {@Material}", Enum.Material.Grass); // Material serialized as: "Enum.Material.Grass" // NumberRange serialization const range = new NumberRange(5, 10); Log.Info("Damage range {@DamageRange}", range); // DamageRange serialized as: { Min: 5, Max: 10 } ``` -------------------------------- ### Conditional Enrichment Based on Log Level Source: https://context7.com/roblox-aurora/rbx-log/llms.txt Demonstrates conditional enrichment where a property ('DebugData') is only added to log events at or above a specified minimum log level (Fatal). ```typescript // Conditional enrichment based on log level Log.SetLogger( Logger.configure() .EnrichWithProperty("DebugData", { detailed: true }, (enricher) => { // Only add DebugData for Fatal messages enricher.SetMinLogLevel(LogLevel.Fatal); }) .WriteTo(Log.RobloxOutput()) .Create() ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.