• Stars
    star
    299
  • Rank 133,855 (Top 3 %)
  • Language
    Objective-C
  • License
    Apache License 2.0
  • Created about 8 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Twitter Logging Service is a robust and performant logging framework for iOS clients

Twitter Logging Service

Background

Twitter created a framework for logging in order to fulfill the following requirements:

  • fast (no blocking the main thread)
  • thread safe
  • as easy as NSLog in most situations
  • support pluggable "output streams" to which messages will be delivered
  • "output streams" filter messages rather than global filtering for all "output streams"
  • able to categorize log messages (log channels)
  • able to designate importance to log messages (log levels)
  • require messages to opt-in for persisted logs (a security requirement, fulfilled by using the context feature of TLS)

Twitter has been using Twitter Logging Service since January 2014 with minimal changes. We've decided to share it with the developer community.

List of good alternative logging frameworks

If Twitter Logging Service doesn't meet your needs, there are many great logging frameworks available, including the following high quality and well maintained projects:

  • CocoaLumberjack
  • SwiftyBeaver
  • Apache Logging Services

Architecture

There are 3 components to consider:

  1. the log message and its context
  2. the logging service instance or singleton
  3. the output stream(s)

The log message is sent to the logging service which provides the message to each output stream.

The logging service is configured by adding discrete output streams. Output streams encapsulate their own behavior and decisions, including filtering and logging messages. For instance, logging can mean printing to console with NSLog, writing to a file on disk, or sending the message to a remote server.

Message arguments don't need to be evaluated if the message is going to be filtered out. This avoids expensive, synchronous execution of argument evaluation. The message is then packaged with context before it is sent to the logging service. Context includes information such as the log level, log channel, file name, function name, line number and timestamp.

The logging service marshals the message and its context to a background queue for processing by all available output streams. Streams can then filter or output the message.

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it using the following command:

    $ gem install cocoapods

To integrate TwitterLoggingService into your Xcode project using CocoaPods, specify it in your Podfile:

    platform :ios, '8.0'
    use_frameworks!

    target "MyApp" do
        pod 'TwitterLoggingService', '~> 2.9.0'
    end

Usage

TLSLog.h is the principal header for using TwitterLoggingService. Just include TLSLog.h or @import TwitterLoggingService.

    // The primary macros for *TwitterLoggingService*

    TLSLogError(channel, ...)          // Log at the TLSLogLevelError level
    TLSLogWarning(channel, ...)        // Log at the TLSLogLevelWarning level
    TLSLogInformation(channel, ...)    // Log at the TLSLogLevelInformation level
    TLSLogDebug(channel, ...)          // Log at the TLSLogLevelDebug level

For each macro in the TLSLog family of macros, TLSCanLog is called first to gate whether the actual logging should occur. This saves us from having to evaluate the arguments to the log message and can provide a win in performance when calling a TLSLog macro that will never end up being logged. For more on TLSCanLog see Gating TLSLog messages below.

TLSLog Core Macro

    #define TLSLog(level, channel, ...)

TLSLog is the core macro and takes 3 parameters: a TLSLogLevel level, an NSString channel and then an NSString format with variable formatting arguments. The level and channel parameters are used to filter the log message per TLSOutputStream in the TLSLoggingService singleton. Providing nil as the channel argument to any logging macro, function or method will result in the message not being logged.

Logging Channels, Levels and Context Objects

Channels

The logging channel of a log message is an arbitrary string and acts as a tag to that message to further help identify what the message relates to. Channels can help to quickly identify what a log message relates to in a large code base, as well as provide a mechanism for filtering. A TLSOutputStream can filter based on the logging channel in its implementation of tls_shouldFilterLevel:channel:contextObject:. Providing a nil channel to a log statement has the effect of not logging that message.

Examples of potential logging channels: @"Networking" for the networking stack, @"SignUp" for an app’s signup flow, TLSLogChannelDefault as a catch all default logging channel, and @"Verbose" for anything you just want to log for the helluvit.

Levels

The enum TLSLogLevel specifies 8 logging levels in accordance with the syslog specification for logging. For practical use, however, only 4 log levels are used: TLSLogLevelError, TLSLogLevelWarning, TLSLogLevelInformation and TLSLogLevelDebug. Each log message has a specified logging level which helps quickly identify its level, TLSLogLevelEmergency (or TLSLogLevelError in practice) is the most important while TLSLogLevelDebug is the least. TLSOutputStream instances can filter a log message by its log level (in combination with its logging channel and context object) by implementing tls_shouldFilterLevel:channel:contextObject:.

An implementation detail to keep in mind w.r.t. logging levels is that TLSLogLevelDebug is ALWAYS filtered out in non-DEBUG builds.

Context Objects

Though the TLSLog macros do not have a context object parameter, one can provide a context object to the TLSLogging APIs in order to provide additional context to custom TLSOutputStreams. The context object will carry through the TLSLoggingService so that it is available to all TLSOutputStream instances. The context object can be used to filter in the tls_shouldFilterLevel:channel:contextObject: method. The context object can also be used for additional information in the logging of a message since it carries to the TLSLogMessageInfo object that's passed to tls_outputLogInfo:.

This context object provides near limitless extensibility to the TLSLogging framework beyond the basics of filtering and logging based on a logging level and logging channel. Twitter uses the context object as a way to secure log messages from leaking to output streams that should not log messages unless explicitely told to do so, thus protecting Personally Identifiable Information from being logged as a default behavior.

Setup

Setting up your project to use TwitterLoggingService:

  1. Add the TwitterLoggingService XCode project as a subproject of your XCode project.

  2. Add the libTwitterLoggingService.a library or TwitterLoggingService.framework framework as a dependency in your XCode project.

  3. Set up your project to build the TwitterLoggingService project with DEBUG=1 in debug builds and RELEASE=1 in release builds.

  4. Set up the TLSLoggingService singleton on application startup (often in application:didFinishLaunchingWithOptions: of your UIApplication's delegate for iOS).

    @import TLSLoggingKit;

    // ...

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options
    {
        // ...

        // Set up the Twitter Logging Service!
        TLSLoggingService *logger = [TLSLoggingService sharedInstance];
    #if DEBUG
        if ([TLSOSLogOutputStream supported]) {
            [logger addOutputStream:[[TLSOSLogOutputStream alloc] init]];
        } else {
            [logger addOutputStream:[[TLSNSLogOutputStream alloc] init]];
        }
    #endif
        [logger addOutputStream:[[TLSFileOutputStream alloc] initWithLogFileName:@"appname-info.log"]];

        // ...
    }

    // ...

    // Someplace else in your project
    - (void)foo
    {
        //  ...

        if (error) {
            TLSLogError(TLSLogChannelDefault, @"Encountered an error while performing foo: %@", error);
        } else {
            TLSLogInformation(@"Verbose", @"foo executed flawlessly!");
        }

        // ...
    }

Best Practices

As a best practice follow these simple guidelines:

  1. Any user sensitive information should not be logged to output streams that persist messages (including being sent over the network to be saved). You can configure your output stream to filter out logs to these sensitive channels. Or do the inverse, and only permit certain "safe" channels to be logged. Twitter has elected to use the pattern where only explicitely "safe" messages (designated via a custom context object) are logged to output streams that will persist. If in doubt, you can log to the TLSLogLevelDebug log level, which is only ever logged in DEBUG builds.

  2. Configure DEBUG builds to have a console output like TLSNSLogOutputStream or TLSStdErrOutputStream - but add only 1 or you'll spam the debug console.

  3. Configure RELEASE builds to not use the console output stream.

  4. Add Crashlytics to your project and add a subclass of the TLSCrashlyticsOutputStream to TLSLoggingService instead of using CLSLog, CLSNSLog or CLS_LOG. You MUST subclass TLSCrashlyticsOutputStream.

TLSLogChannelApplicationDefault function

    FOUNDATION_EXTERN NSString *TLSLogChannelApplicationDefault() __attribute__((const));
    #define TLSLogChannelDefault TLSLogChannelApplicationDefault()

Retrieve a channel based on the application. You can use this as a default channel.

Loads and caches the channel name in the following order of descending priority:

  1. kCFBundleNameKey of main bundle

  2. kCFBundleExecutableKey of main bundle

  3. Binary executable name

  4. @"Default"

The default channel is available as a convenience for quick logging. However, it is recommended to always have concrete, well-defined logging channels to which output is logged (e.g. "Networking", "UI", "Model", "Cache", et al).

TLSLog Helper Functions

There are a number of TLSLog Helper Functions and they all accept as a first parameter a TLSLoggingService. If nil is provided for the service parameter, the shared [TLSLoggingService sharedInstance] will be used. All TLSLog macros use nil for the service parameter, but if there is different instance to be used, these helper functions support that. As an example, Twitter extends TwitterLoggingService with its own set of macros so that a context is provided that defines the duration for which a message can be safely retained (e.g. to avoid retaining sensitive information), and uses custom macros that call these helper functions.

Gating TLSLog messages

    BOOL TLSCanLog(TLSLoggingService *service, TLSLogLevel level, NSString *channel, id contextObject); // gate for logging TLSLog messages

At the moment, TLSCanLog evaluates two things (contextObject is currently ignored): the cached permitted log levels and the cached not permitted log channels. A log message can log given the desired level is permitted by the internal cache of known permitted TLSLogLevels based on the outputStreams of TLSLoggingService AND the given log channel has not been cached as a known to be an always off channel (for TLSLOGMODE=1 that is, see below for different behaviors).

TLSCANLOGMODE build setting

TwitterLoggingService supports being compiled in one of 3 different modes:

  • TLSCANLOGMODE=0
  • TLSCanLog will always return YES
  • Log arguments always evaluate, which can be inefficient for args that won't log
  • TLSCANLOGMODE=1
  • TLSCanLog will base its return value on cached insight into what can and cannot be logged
  • This will save on argument evalution at the minimal cost of a quick lookup of cached information
  • This is the default if TLSCANLOGMODE is not defined
  • TLSCANLOGMODE=2
  • TLSCanLog will base its return value on the filtering behavior of all the registered output streams
  • This will save on argument evalution but requires an expensive examination of all output streams

License

Copyright 2013-2020 Twitter, Inc.

Licensed under the Apache License, Version 2.0: https://www.apache.org/licenses/LICENSE-2.0

Security Issues?

Please report sensitive security issues via Twitter's bug-bounty program (https://hackerone.com/twitter) rather than GitHub.

More Repositories

1

the-algorithm

Source code for Twitter's Recommendation Algorithm
Scala
60,968
star
2

twemoji

Emoji for everyone. https://twemoji.twitter.com/
HTML
16,575
star
3

typeahead.js

typeahead.js is a fast and fully-featured autocomplete library
JavaScript
16,526
star
4

twemproxy

A fast, light-weight proxy for memcached and redis
C
12,000
star
5

the-algorithm-ml

Source code for Twitter's Recommendation Algorithm
Python
9,844
star
6

finagle

A fault tolerant, protocol-agnostic RPC system
Scala
8,742
star
7

hogan.js

A compiler for the Mustache templating language
JavaScript
5,143
star
8

labella.js

Placing labels on a timeline without overlap.
JavaScript
3,869
star
9

scala_school

Lessons in the Fundamentals of Scala
HTML
3,700
star
10

AnomalyDetection

Anomaly Detection with R
R
3,529
star
11

scalding

A Scala API for Cascading
Scala
3,467
star
12

twitter-text

Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.
HTML
3,051
star
13

TwitterTextEditor

A standalone, flexible API that provides a full-featured rich text editor for iOS applications.
Swift
2,950
star
14

opensource-website

Twitter's open source website, identifying projects we've released, organizations we support, and the work we do to support open source.
SCSS
2,918
star
15

util

Wonderful reusable code from Twitter
Scala
2,679
star
16

algebird

Abstract Algebra for Scala
Scala
2,284
star
17

finatra

Fast, testable, Scala services built on TwitterServer and Finagle
Scala
2,271
star
18

effectivescala

Twitter's Effective Scala Guide
HTML
2,241
star
19

summingbird

Streaming MapReduce with Scalding and Storm
Scala
2,136
star
20

pelikan

Pelikan is Twitter's unified cache backend
C
1,921
star
21

ios-twitter-image-pipeline

Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients
C
1,851
star
22

twurl

OAuth-enabled curl for the Twitter API
Ruby
1,790
star
23

twitter-server

Twitter-Server defines a template from which services at Twitter are built
Scala
1,542
star
24

rezolus

Systems performance telemetry
Rust
1,541
star
25

activerecord-reputation-system

An Active Record Reputation System for Rails
Ruby
1,334
star
26

communitynotes

Documentation and source code powering Twitter's Community Notes
Python
1,319
star
27

compose-rules

Static checks to aid with a healthy adoption of Compose
Kotlin
1,311
star
28

fatcache

Memcache on SSD
C
1,301
star
29

rsc

Experimental Scala compiler focused on compilation speed
Scala
1,245
star
30

elephant-bird

Twitter's collection of LZO and Protocol Buffer-related Hadoop, Pig, Hive, and HBase code.
Java
1,137
star
31

cassovary

Cassovary is a simple big graph processing library for the JVM
Scala
1,039
star
32

Serial

Light-weight, fast framework for object serialization in Java, with Android support.
Java
988
star
33

hbc

A Java HTTP client for consuming Twitter's realtime Streaming API
Java
963
star
34

twemcache

Twemcache is the Twitter Memcached
C
925
star
35

innovators-patent-agreement

Innovators Patent Agreement (IPA)
919
star
36

vireo

Vireo is a lightweight and versatile video processing library written in C++11
C++
919
star
37

twitter-korean-text

Korean tokenizer
Scala
834
star
38

scrooge

A Thrift parser/generator
Scala
785
star
39

BreakoutDetection

Breakout Detection via Robust E-Statistics
C++
753
star
40

GraphJet

GraphJet is a real-time graph processing library.
Java
696
star
41

twitter-cldr-rb

Ruby implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more.
Ruby
667
star
42

bijection

Reversible conversions between types
Scala
657
star
43

chill

Scala extensions for the Kryo serialization library
Scala
607
star
44

ios-twitter-network-layer

Twitter Network Layer is a scalable and feature rich network layer built on top of NSURLSession for Apple platforms
Objective-C
573
star
45

hadoop-lzo

Refactored version of code.google.com/hadoop-gpl-compression for hadoop 0.20
Shell
544
star
46

storehaus

Storehaus is a library that makes it easy to work with asynchronous key value stores
Scala
464
star
47

rpc-perf

A tool for benchmarking RPC services
Rust
458
star
48

d3kit

D3Kit is a set tools to speed D3 related project development
JavaScript
429
star
49

scoot

Scoot is a distributed task runner, supporting both a proprietary API and Bazel's Remote Execution.
Go
347
star
50

twitter-cldr-js

JavaScript implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more. Based on twitter-cldr-rb.
JavaScript
345
star
51

scala_school2

Scala School 2
Scala
340
star
52

rustcommon

Common Twitter Rust lib
Rust
339
star
53

wordpress

The official Twitter plugin for WordPress. Embed Twitter content and grow your audience on Twitter.
PHP
310
star
54

nodes

A library to implement asynchronous dependency graphs for services in Java
Java
246
star
55

SentenTree

A novel text visualization technique
JavaScript
226
star
56

interactive

Twitter interactive visualization
HTML
213
star
57

joauth

A Java library for authenticating HTTP Requests using OAuth
Java
211
star
58

thrift_client

A Thrift client wrapper that encapsulates some common failover behavior
Ruby
196
star
59

hpack

Header Compression for HTTP/2
Java
192
star
60

zktraffic

ZooKeeper protocol analyzer and stats gathering daemon
Python
165
star
61

twemoji-parser

A simple library for identifying emoji entities within a string in order to render them as Twemoji.
Scala
162
star
62

cache-trace

A collection of Twitter's anonymized production cache traces.
Shell
162
star
63

sbf

Java
159
star
64

tormenta

Scala extensions for Storm
Scala
132
star
65

whiskey

HTTP library for Android (beta)
Java
131
star
66

hraven

hRaven collects run time data and statistics from MapReduce jobs in an easily queryable format
Java
127
star
67

netty-http2

HTTP/2 for Netty
Java
120
star
68

sqrl

A Safe, Stateful Rules Language for Event Streams
TypeScript
100
star
69

ccommon

Cache Commons
C
99
star
70

focus

Focus aligns Git worktree content based on outlines of a repository's Bazel build graph. Focused repos are sparse, shallow, and thin and unlock markedly better performance in large repos.
Rust
91
star
71

dict_minimize

Access scipy optimizers from your favorite deep learning framework.
Python
77
star
72

metrics

76
star
73

twitter.github.io

HTML
71
star
74

go-bindata

Go
68
star
75

diffusion-rl

Python
66
star
76

birdwatch

64
star
77

cloudhopper-commons

Cloudhopper Commons
Java
57
star
78

twitter-cldr-npm

TwitterCldr npm package
JavaScript
49
star
79

.github

Twitter GitHub Organization-wide files
48
star
80

bazel-multiversion

Bazel rules to resolve, fetch and manage 3rdparty JVM dependencies with support for multiple parallel versions of the same dependency. Powered by Coursier.
Scala
47
star
81

libwatchman

A C interface to watchman
C
44
star
82

sslconfig

Twitter's OpenSSL Configuration
42
star
83

ios-twitter-apache-thrift

A thrift encoding and decoding library for Swift
Swift
41
star
84

gatekeeper-service

GateKeeper is a service built to automate the manual steps involved in onboarding, offboarding, and lost asset scenarios.
Python
36
star
85

dodo

The Twitter OSS Project Builder
Shell
35
star
86

repo-scaffolding

Tools for creating repos based on open source standards and best practices
33
star
87

iago2

A load generator, built for engineers
Scala
24
star
88

caladrius

Performance modelling system for Distributed Stream Processing Systems (DSPS) such as Apache Heron and Apache Storm
Python
22
star
89

ossdecks

Repository for Twitter Open Source Decks
10
star
90

curation-style-guide

Document Repository for Twitter's Curation Style Guide
10
star
91

analytics-infra-governance

Description of the process for how to commit, review, and release code to the Scalding OSS family (Scalding, Summingbird, Algebird, Bijection, Storehaus, etc)
9
star
92

gpl-commitment

Twitter's GPL Cooperation Commitment
5
star
93

second-control-probability-distributions

4
star
94

google-tag-manager-event-tag

Smarty
3
star
95

google-tag-manager-base-tag

Smarty
2
star