/

User Identification

User Identification

Track which users are performing actions and experiencing errors by identifying them in your logs. This enables powerful filtering, debugging, and user impact analysis.

AuthUser Structure

Create an AuthUser instance with user information:

Python
from bytehide_logs import AuthUser

user = AuthUser(
    id="user_12345",
    email="alice@company.com",
    token="token_abc123xyz"
)

The AuthUser constructor accepts:

  • id (required) - Unique identifier for the user
  • email (optional) - User's email address
  • token (optional) - Authentication token (will be masked)

Identifying Users

Use Log.identify() to associate subsequent logs with a user:

Python
from bytehide_logs import Log, AuthUser

user = AuthUser(
    id="user_42",
    email="bob@example.com",
    token="secret_token_xyz"
)

Log.identify(user)

# All subsequent logs are now associated with user_42
Log.info("User session created")
Log.info("Processing user preferences")
Log.info("Saving profile changes")

Updating Previous Logs

The update_previous_logs parameter allows you to retroactively associate a user with earlier logs:

Python
# Initial logs without user context
Log.info("Request received")
Log.info("Validating credentials")

# User identified after initial logs
user = AuthUser(id="user_789", email="charlie@example.com")
Log.identify(user, update_previous_logs=True)

# Now earlier logs are associated with this user
Log.info("User authenticated successfully")

Set update_previous_logs=False (default) to only identify the current and future logs:

Python
# Initial logs
Log.info("Processing request")

# Identify user for current and future logs only
Log.identify(user, update_previous_logs=False)

# This log is associated with the user
Log.info("Request completed successfully")

User Logout

End a user session with Log.logout():

Python
Log.logout()

# Subsequent logs are no longer associated with the previous user
Log.info("User session ended")

Use logout when:

  • User explicitly logs out
  • Session expires or is revoked
  • User switches accounts
  • Cleaning up after user operations

Complete Authentication Flow

Python
from bytehide_logs import Log, AuthUser

def handle_login(credentials):
    """Handle user login with comprehensive logging."""
    Log.info("Login attempt", context={"email": credentials.email})
    
    try:
        # Validate credentials
        user_data = authenticate(credentials)
        
        # Create AuthUser
        user = AuthUser(
            id=user_data.id,
            email=user_data.email,
            token=user_data.session_token
        )
        
        # Identify user for all subsequent logs
        Log.identify(user)
        
        Log.info("User authentication successful")
        return user_data
        
    except AuthenticationError as e:
        Log.warning(
            "Login failed",
            exception=e,
            context={"email": credentials.email}
        )
        raise

def handle_logout():
    """Handle user logout."""
    Log.info("User logout initiated")
    
    # Perform logout operations
    clear_session()
    
    # Disassociate user from logs
    Log.logout()
    
    Log.info("User session terminated")

Identifying Different Users

Switch between users by calling identify() again:

Python
# Initial user
user_alice = AuthUser(id="alice_001", email="alice@example.com")
Log.identify(user_alice)
Log.info("Alice performed action")

# Switch to different user
user_bob = AuthUser(id="bob_001", email="bob@example.com")
Log.identify(user_bob)
Log.info("Bob performed action")

# Logout
Log.logout()
Log.info("No user context")

Using User Context with Tags and Correlation IDs

Combine user identification with other context:

Python
user = AuthUser(id="user_456", email="dave@example.com")
Log.identify(user)

Log.with_tags("user_action", "profile") \
    .with_context("action", "update_bio") \
    .with_correlation_id("req_78910") \
    .info("User profile updated successfully")

Privacy and Security

The token field is automatically masked:

Python
user = AuthUser(
    id="user_999",
    email="secure@example.com",
    token="super_secret_token_12345"
)

Log.identify(user)
Log.info("User identified")
# Token is masked in logs automatically

See data masking for more information about protecting sensitive data.

Accessing Current User

Query the currently identified user:

Python
from bytehide_logs import Log

# Get current user context
current_user = Log.get_current_user()

if current_user:
    print(f"Logged in as: {current_user.email}")
else:
    print("No user identified")

Best Practices

Identify users early in your request handling:

Python
# Good - identify before processing
def handle_request(request):
    user = get_user_from_token(request.headers["Authorization"])
    Log.identify(user)
    
    # All downstream logs have user context
    process_request(request)

Use update_previous_logs carefully:

Python
# Use update_previous_logs=True for:
# - Deferred authentication (identify after logging begins)
# - Retry loops with late authentication

# Use update_previous_logs=False (default) for:
# - Standard authentication before processing
# - Avoiding re-indexing large log sets

Always logout when appropriate:

Python
# Good - explicit logout
try:
    handle_request(request)
finally:
    Log.logout()

Next Steps

  • Learn about tags to categorize user actions
  • Explore correlation IDs to track user requests across services
  • Discover data masking to protect user tokens and sensitive data
Previous
Data Masking