/

Quick Start with ByteHide Logger

Prerequisites

Before you begin, make sure you have:

  • A ByteHide account and project token
  • Java 8+ installed (or Android API 21+ for mobile)

Quick Start Guide

  1. Install ByteHide Logger in your project
  2. Initialize the logger with your project token
  3. Start logging with simple API calls
  4. View logs in the ByteHide web panel
  5. Explore advanced features as needed

Step 1: Installation

Add the ByteHide Logger dependency to your project:

Maven

XML
<dependency>
    <groupId>com.bytehide</groupId>
    <artifactId>bytehide-logs</artifactId>
    <version>1.0.0</version>
</dependency>

Gradle

GRADLE
implementation 'com.bytehide:bytehide-logs:1.0.0'

Step 2: Basic Setup

Initialize the logger in your application startup:

Java
import com.bytehide.logs.core.Log;
import com.bytehide.logs.models.LogLevel;

public class Application {
    public static void main(String[] args) {
        // Configure the logger
        Log.setProjectToken("your-project-token-here");
        Log.setMinimumLevel(LogLevel.INFO);
        Log.setConsoleEnabled(true);
        Log.setPersist(true);
        Log.setFilePath("logs/app.log");

        // Your application code
        runApplication();
    }

    static void runApplication() {
        Log.info("Application started successfully!");
        
        try {
            // Simulate some work
            processOrder("ORD-001", "CUST-123");
        } catch (Exception e) {
            Log.error("Application error occurred", e);
        } finally {
            Log.info("Application finished");
            Log.flush();
            Log.shutdown();
        }
    }

    static void processOrder(String orderId, String customerId) {
        Log.withContext("orderId", orderId)
           .withContext("customerId", customerId)
           .info("Processing order");

        // Simulate processing time
        try { Thread.sleep(1000); } catch (InterruptedException ignored) {}

        Log.withContext("orderId", orderId)
           .withContext("processingTime", "1.2s")
           .info("Order processed successfully");
    }
}

Step 3: Basic Logging

Use the simple logging API throughout your application:

Java
import com.bytehide.logs.core.Log;

public class UserService {
    public User getUser(String userId) {
        Log.debug("Fetching user with ID: " + userId);

        try {
            User user = database.getUser(userId);
            
            Log.withContext("userId", userId)
               .withContext("username", user.getUsername())
               .info("User retrieved successfully");
            
            return user;
        } catch (UserNotFoundException e) {
            Log.warn("User not found: " + userId);
            throw e;
        } catch (Exception e) {
            Log.error("Failed to retrieve user", e);
            throw e;
        }
    }

    public void createUser(User user) {
        Log.withContext("username", user.getUsername())
           .withContext("email", user.getEmail())
           .info("Creating new user");

        try {
            database.createUser(user);
            Log.withContext("userId", user.getId())
               .info("User created successfully");
        } catch (Exception e) {
            Log.error("Failed to create user", e);
            throw e;
        }
    }
}

Step 4: Advanced Logging Features

Structured Logging with Context

Java
// Add context to your logs
Log.withContext("userId", "12345")
   .withContext("sessionId", "sess-abc")
   .info("User performed action");

// Use tags for categorization
Log.withTags("payment", "critical")
   .info("Payment processing started");

// Combine context and tags
Log.withContext("orderId", "ORD-001")
   .withContext("amount", 99.99)
   .withTags("payment", "success")
   .info("Payment completed");

User Identification

Java
import com.bytehide.logs.models.AuthUser;

// Identify the current user
AuthUser user = new AuthUser();
user.setId("user-123");
user.setEmail("john.doe@company.com");
user.setName("John Doe");
Log.setUser(user);

// All subsequent logs will include user information
Log.info("User action performed");
Log.warn("User attempted unauthorized action");

Correlation IDs

Java
// Set correlation ID for request tracking
String correlationId = "req_" + System.currentTimeMillis();

Log.withCorrelationId(correlationId).info("Request started");
Log.withCorrelationId(correlationId).info("Processing data");
Log.withCorrelationId(correlationId).info("Request completed");

Step 5: Production Configuration

For production environments, use a more comprehensive configuration:

Java
import com.bytehide.logs.core.Log;
import com.bytehide.logs.models.LogLevel;
import com.bytehide.logs.models.RollingInterval;

public class ProductionConfig {
    public static void initialize() {
        // Log levels
        Log.setMinimumLevel(LogLevel.WARN);
        
        // File logging
        Log.setPersist(true);
        Log.setFilePath("logs/production.log");
        Log.setRollingInterval(RollingInterval.DAY);
        
        // Security
        Log.addSensitiveKey("password");
        Log.addSensitiveKey("token");
        Log.addSensitiveKey("secret");
        Log.addSensitiveKey("apiKey");
        Log.addSensitiveKey("creditCard");
        
        // Performance
        Log.setDuplicateSuppressionWindow(10000L);
        
        // Disable console in production
        Log.setConsoleEnabled(false);
        
        // Use environment variable for project token
        Log.setProjectToken(System.getenv("BYTEHIDE_LOGS_TOKEN"));
    }
}

Step 6: View Your Logs

After your application runs, you can view logs in multiple places:

Console Output (Development)

CODE
[2024-01-15 10:30:15] [Info] Application started successfully!
[2024-01-15 10:30:15] [Info] Processing order { orderId: "ORD-001", customerId: "CUST-123" }
[2024-01-15 10:30:16] [Info] Order processed successfully { orderId: "ORD-001", processingTime: "1.2s" }

Log Files

Check your configured log file path (e.g., logs/app.log):

CODE
2024-01-15 10:30:15.123 [INFO] Application started successfully!
2024-01-15 10:30:15.456 [INFO] Processing order orderId=ORD-001 customerId=CUST-123
2024-01-15 10:30:16.789 [INFO] Order processed successfully orderId=ORD-001 processingTime=1.2s

ByteHide Web Panel

  1. Log in to ByteHide Cloud
  2. Select your Logs project
  3. View real-time logs, search, filter, and analyze

Common Patterns

Error Handling

Java
public ApiResponse processRequest(Request request) {
    String correlationId = java.util.UUID.randomUUID().toString();

    try {
        Log.withCorrelationId(correlationId)
           .withContext("requestId", request.getId())
           .withContext("type", request.getType())
           .info("Request received");

        Result result = processBusinessLogic(request);
        
        Log.withCorrelationId(correlationId)
           .withContext("requestId", request.getId())
           .withContext("resultCount", result.getItems().size())
           .info("Request processed successfully");

        return ApiResponse.success(result);
    } catch (ValidationException e) {
        Log.withCorrelationId(correlationId)
           .withContext("requestId", request.getId())
           .withException(e)
           .warn("Request validation failed");
        return ApiResponse.badRequest(e.getMessage());
    } catch (Exception e) {
        Log.withCorrelationId(correlationId)
           .withException(e)
           .error("Request processing failed");
        return ApiResponse.internalServerError();
    }
}

Performance Monitoring

Java
public List<Product> getProducts(int categoryId) {
    long startTime = System.currentTimeMillis();
    
    try {
        List<Product> products = repository.getProductsByCategory(categoryId);
        
        long elapsed = System.currentTimeMillis() - startTime;
        
        Log.withContext("categoryId", categoryId)
           .withContext("productCount", products.size())
           .withContext("elapsedMs", elapsed)
           .info("Products retrieved");
        
        return products;
    } catch (Exception e) {
        long elapsed = System.currentTimeMillis() - startTime;
        
        Log.withContext("categoryId", categoryId)
           .withContext("elapsedMs", elapsed)
           .withException(e)
           .error("Failed to retrieve products");
        
        throw e;
    }
}

Next Steps

Now that you have basic logging working:

Previous
Configuration