|
| 1 | +// Copyright 2018 Sourcerer Inc. All Rights Reserved. |
| 2 | +// Author: Alexander Surkov ([email protected]) |
| 3 | + |
| 4 | +package sourcererio.vacuumanalytics |
| 5 | + |
| 6 | +import com.github.kittinunf.fuel.core.FuelError |
| 7 | +import com.github.kittinunf.fuel.core.FuelManager |
| 8 | +import com.github.kittinunf.fuel.core.Method |
| 9 | +import com.github.kittinunf.fuel.core.Request |
| 10 | +import com.github.kittinunf.fuel.core.Response |
| 11 | +import java.net.HttpCookie |
| 12 | +import java.util.Date |
| 13 | + |
| 14 | +/** |
| 15 | + * Elastic LogStash logging. |
| 16 | + */ |
| 17 | +class LogEvent { |
| 18 | + // Unique identifier of the session. |
| 19 | + private var session: String = "" |
| 20 | + |
| 21 | + private val fuelManager = FuelManager() |
| 22 | + |
| 23 | + /** |
| 24 | + * Creates a LogEvent instance. |
| 25 | + * |
| 26 | + * @param path [in] path to send logs to, |
| 27 | + * @param res [in] HTTP response of successful user authorization, |
| 28 | + * @param sid [in] session id of the HTTP response. |
| 29 | + */ |
| 30 | + constructor(path: String, |
| 31 | + res: Response, sid: String) { |
| 32 | + res.headers["Set-Cookie"]?. |
| 33 | + flatMap { HttpCookie.parse(it) }?. |
| 34 | + find { it.name == sid }?. |
| 35 | + let { session = it.value } |
| 36 | + |
| 37 | + fuelManager.basePath = path |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Logs error. |
| 42 | + */ |
| 43 | + fun error(message: String) { |
| 44 | + event("error", message) |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Logs event. |
| 49 | + */ |
| 50 | + fun event(type: String, message: String) { |
| 51 | + event(type, listOf("message" to message)) |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Logs event. |
| 56 | + */ |
| 57 | + fun event(type: String, fields: List<Pair<String, Any?>>) { |
| 58 | + var params = mutableListOf<Pair<String, Any?>>( |
| 59 | + "session" to session, |
| 60 | + "type" to type, |
| 61 | + "timestamp" to Date().getTime() |
| 62 | + ) |
| 63 | + |
| 64 | + fuelManager. |
| 65 | + request( |
| 66 | + Method.POST, |
| 67 | + "", |
| 68 | + params.plus(fields) |
| 69 | + ) |
| 70 | + .response { _, _, result -> |
| 71 | + val (_, err) = result |
| 72 | + if (err != null) { |
| 73 | + throw Exception("FAILED to send logs: $err") |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments