or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-communication.mdcore-sender.mdevent-interface.mdindex.mdlogging-integration.md

event-interface.mddocs/

0

# Event-Based Interface

1

2

Simplified API wrapper using global sender instances for quick integration and reduced boilerplate code. This interface provides the easiest way to send events to Fluentd with minimal setup.

3

4

## Capabilities

5

6

### Global Setup Functions

7

8

Module-level functions for initializing and managing a global sender instance, eliminating the need to pass sender objects throughout the application.

9

10

```python { .api }

11

def setup(tag: str, **kwargs) -> None:

12

"""

13

Initialize global FluentSender instance.

14

15

Parameters:

16

- tag (str): Tag prefix for all events

17

- **kwargs: FluentSender constructor arguments (host, port, timeout, etc.)

18

"""

19

20

def get_global_sender():

21

"""

22

Get the global FluentSender instance.

23

24

Returns:

25

FluentSender or None: The global sender instance

26

"""

27

28

def close() -> None:

29

"""Close and cleanup the global FluentSender instance."""

30

```

31

32

### Event Class

33

34

Simple event creation and emission class that automatically uses the global sender instance.

35

36

```python { .api }

37

class Event:

38

def __init__(self, label: str, data: dict, **kwargs):

39

"""

40

Create and immediately send an event.

41

42

Parameters:

43

- label (str): Event label (combined with global tag)

44

- data (dict): Event data dictionary (must be a dict)

45

- sender (FluentSender, optional): Custom sender instance, defaults to global

46

- time (timestamp, optional): Custom timestamp, defaults to current time

47

48

Raises:

49

AssertionError: If data is not a dictionary

50

"""

51

```

52

53

## Usage Examples

54

55

### Basic Event-Based Logging

56

57

```python

58

from fluent import sender, event

59

60

# Setup global sender once at application start

61

sender.setup('myapp')

62

63

# Send events anywhere in the application

64

event.Event('user.login', {

65

'user_id': 123,

66

'username': 'alice',

67

'ip_address': '192.168.1.100'

68

})

69

70

event.Event('user.action', {

71

'user_id': 123,

72

'action': 'view_page',

73

'page': '/dashboard',

74

'duration_ms': 250

75

})

76

77

# Cleanup at application shutdown

78

sender.close()

79

```

80

81

### Remote Fluentd Configuration

82

83

```python

84

from fluent import sender, event

85

86

# Setup with remote Fluentd server

87

sender.setup('webapp', host='logs.company.com', port=24224, timeout=5.0)

88

89

# Events are automatically sent to remote server

90

event.Event('order.created', {

91

'order_id': 'ord-12345',

92

'user_id': 456,

93

'total_amount': 89.99,

94

'currency': 'USD',

95

'items_count': 3

96

})

97

98

event.Event('payment.processed', {

99

'order_id': 'ord-12345',

100

'payment_method': 'credit_card',

101

'transaction_id': 'txn-67890'

102

})

103

104

sender.close()

105

```

106

107

### Custom Timestamps

108

109

```python

110

import time

111

from fluent import sender, event

112

113

sender.setup('analytics')

114

115

# Event with current timestamp (default)

116

event.Event('page.view', {

117

'url': '/products/123',

118

'user_agent': 'Mozilla/5.0...',

119

'referrer': 'https://google.com'

120

})

121

122

# Event with specific timestamp

123

custom_time = int(time.time()) - 3600 # 1 hour ago

124

event.Event('historical.data', {

125

'metric': 'cpu_usage',

126

'value': 75.5,

127

'host': 'server-01'

128

}, time=custom_time)

129

130

sender.close()

131

```

132

133

### Using Custom Sender

134

135

```python

136

from fluent import sender, event

137

138

# Setup default global sender

139

sender.setup('app')

140

141

# Create custom sender for special events

142

critical_sender = sender.FluentSender(

143

'critical',

144

host='alerts.company.com',

145

port=24224,

146

timeout=1.0

147

)

148

149

# Use global sender

150

event.Event('info', {'message': 'User logged in'})

151

152

# Use custom sender for critical events

153

event.Event('system.error', {

154

'error_code': 500,

155

'message': 'Database connection failed',

156

'severity': 'critical'

157

}, sender=critical_sender)

158

159

# Cleanup

160

sender.close()

161

critical_sender.close()

162

```

163

164

### Error Handling with Event Interface

165

166

```python

167

from fluent import sender, event

168

169

# Setup with error handling configuration

170

sender.setup('app', host='unreliable-host.example.com', verbose=True)

171

172

# The Event class doesn't return success/failure status

173

# To check for errors, access the global sender directly

174

event.Event('test', {'data': 'some data'})

175

176

# Check for errors on global sender

177

global_sender = sender.get_global_sender()

178

if global_sender.last_error:

179

print(f"Error occurred: {global_sender.last_error}")

180

global_sender.clear_last_error()

181

182

sender.close()

183

```

184

185

### Integration with Application Lifecycle

186

187

```python

188

from fluent import sender, event

189

import atexit

190

191

class FluentLogger:

192

def __init__(self, app_name, **config):

193

self.app_name = app_name

194

sender.setup(app_name, **config)

195

atexit.register(self.cleanup)

196

197

def log_event(self, event_type, data):

198

event.Event(event_type, data)

199

200

def cleanup(self):

201

sender.close()

202

203

# Application setup

204

logger = FluentLogger('ecommerce', host='logs.example.com')

205

206

# Use throughout application

207

def handle_user_signup(user_data):

208

logger.log_event('user.signup', {

209

'user_id': user_data['id'],

210

'email': user_data['email'],

211

'signup_method': 'email',

212

'referral_code': user_data.get('referral')

213

})

214

215

def handle_purchase(order_data):

216

logger.log_event('order.completed', {

217

'order_id': order_data['id'],

218

'user_id': order_data['user_id'],

219

'amount': order_data['total'],

220

'currency': order_data['currency'],

221

'product_count': len(order_data['items'])

222

})

223

224

# Events are automatically sent, cleanup happens at exit

225

```

226

227

### Batch Event Logging

228

229

```python

230

from fluent import sender, event

231

232

sender.setup('batch_processor')

233

234

# Process multiple events in a batch

235

events_data = [

236

{'type': 'click', 'user_id': 1, 'element': 'button-a'},

237

{'type': 'scroll', 'user_id': 1, 'position': 50},

238

{'type': 'click', 'user_id': 2, 'element': 'link-b'},

239

{'type': 'pageview', 'user_id': 2, 'page': '/products'}

240

]

241

242

for event_data in events_data:

243

event_type = event_data.pop('type') # Remove type from data

244

event.Event(f'user.{event_type}', event_data)

245

246

sender.close()

247

```