├── .gitignore ├── LICENSE.md ├── README.md ├── config ├── config.exs ├── dev.exs ├── prod.exs └── test.exs ├── lib ├── json_logger.ex └── json_logger │ └── tcp_client.ex ├── mix.exs ├── mix.lock └── test ├── json_logger_tcp_test.exs ├── json_logger_udp_test.exs └── test_helper.exs /.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | /deps 3 | erl_crash.dump 4 | *.ez 5 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Elixir JSON Logger 2 | ================== 3 | 4 | JSON Logger is a logger backend that outputs elixir logs in JSON format. 5 | 6 | This project is originally designed to make Elixir apps work with Logstash easily. It aims at providing as much information for the log is possible, so the logs can be more easily analyzed by backend services like _Elasticsearch_. 7 | 8 | Issues and PRs are welcome. 9 | 10 | ## Dependencies 11 | 12 | This project requires [json](https://hex.pm/packages/json). 13 | 14 | ## Configuration 15 | 16 | ### Elixir Project 17 | 18 | JSON Logger currently provides very few options: 19 | 20 | * __level__: The minimal level of logging. There's no default of this option. Example: `level: :warn` 21 | * __output__: The output of the log. Must be either `:console` or `{:udp, host, port}` or `{:tcp, host, port}. Example: `output: {:udp, "localhost", 514}` 22 | * __metadata__: Whatever else you want in the log. Example: `metadata: "Some very important project"` 23 | 24 | Example configuration: `config :logger, :json_logger, level: :info, output: {:udp, "localhost", 514}` 25 | 26 | **TCP support is still experimental, please submit issues that you encounter.** 27 | 28 | 29 | ### In your application 30 | 31 | You should add `json_logger` to your `mix.exs` as well. This step may not be necessary (if you know why please tell me). 32 | 33 | ```elixir 34 | defmodule MyMod.Mixfile do 35 | # ... 36 | def application do 37 | [applications: [:logger, :json_logger], 38 | mod: {MyMod, []}] 39 | end 40 | # ... 41 | end 42 | ``` 43 | 44 | ### Adding the logger backend 45 | 46 | You need to add this backend to your `Logger`, preferably put this in your `Application`'s `start/2`. 47 | 48 | ```elixir 49 | Logger.add_backend Logger.Backends.JSON 50 | ``` 51 | 52 | ### If you wish to use Logstash with this library 53 | 54 | Here is an example logstash configuration: 55 | 56 | ``` 57 | input { 58 | udp { 59 | port => 514 60 | type => "elixir_json_logging" 61 | } 62 | } 63 | 64 | filter { 65 | json { 66 | source => "message" 67 | } 68 | } 69 | 70 | output { 71 | stdout { 72 | codec => rubydebug 73 | } 74 | } 75 | ``` 76 | 77 | Note that this configuration will probably break on your system (listening to a <1024 port). You **should** change the "port" to a larger value. 78 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Mix.Config module. 3 | use Mix.Config 4 | 5 | # This configuration is loaded before any dependency and is restricted 6 | # to this project. If another project depends on this project, this 7 | # file won't be loaded nor affect the parent project. For this reason, 8 | # if you want to provide default values for your application for third- 9 | # party users, it should be done in your mix.exs file. 10 | 11 | # Sample configuration: 12 | # 13 | # config :logger, :console, 14 | # level: :info, 15 | # format: "$date $time [$level] $metadata$message\n", 16 | # metadata: [:user_id] 17 | 18 | # It is also possible to import configuration files, relative to this 19 | # directory. For example, you can emulate configuration per environment 20 | # by uncommenting the line below and defining dev.exs, test.exs and such. 21 | # Configuration from the imported file will override the ones defined 22 | # here (which is why it is important to import them last). 23 | # 24 | import_config "#{Mix.env}.exs" 25 | -------------------------------------------------------------------------------- /config/dev.exs: -------------------------------------------------------------------------------- 1 | [] 2 | -------------------------------------------------------------------------------- /config/prod.exs: -------------------------------------------------------------------------------- 1 | [] 2 | -------------------------------------------------------------------------------- /config/test.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | 3 | config :logger, :json_logger, 4 | level: :debug 5 | -------------------------------------------------------------------------------- /lib/json_logger.ex: -------------------------------------------------------------------------------- 1 | defmodule Logger.Backends.JSON do 2 | alias Logger.Backends.JSON.TCPClient 3 | use GenEvent 4 | 5 | def init(_) do 6 | if user = Process.whereis(:user) do 7 | Process.group_leader(self(), user) 8 | {:ok, configure([])} 9 | else 10 | {:error, :ignore} 11 | end 12 | end 13 | 14 | def handle_call({:configure, options}, state) do 15 | {:ok, :ok, configure(options, state)} 16 | end 17 | 18 | def handle_event({_level, gl, _event}, state) when node(gl) != node() do 19 | {:ok, state} 20 | end 21 | 22 | def handle_event({level, _gl, {Logger, msg, ts, md}}, %{level: min_level} = state) do 23 | if is_nil(min_level) or Logger.compare_levels(level, min_level) != :lt do 24 | log_event(level, msg, ts, md, state) 25 | end 26 | {:ok, state} 27 | end 28 | 29 | def terminate(_reason, %{output: {:udp, _host, _port, socket}}) do 30 | :gen_udp.close(socket) 31 | :ok 32 | end 33 | 34 | def terminate(_reason, %{output: {:tcp, client}}) do 35 | TCPClient.stop client 36 | :ok 37 | end 38 | 39 | ## Helpers 40 | 41 | defp configure(options, %{output: {:udp, _host, _port, socket}}) do 42 | :gen_udp.close(socket) 43 | configure(options) 44 | end 45 | 46 | defp configure(options, %{output: {:tcp, client}}) do 47 | TCPClient.stop client 48 | configure(options) 49 | end 50 | 51 | defp configure(options, _state) do 52 | configure(options) 53 | end 54 | 55 | defp configure(options) do 56 | json_logger = Keyword.merge(Application.get_env(:logger, :json_logger, []), options) 57 | Application.put_env(:logger, :json_logger, json_logger) 58 | 59 | level = Keyword.get(json_logger, :level) 60 | metadata = Keyword.get(json_logger, :metadata, []) 61 | output = Keyword.get(json_logger, :output, :console) 62 | output = case output do 63 | :console -> :console 64 | {:udp, host, port} -> 65 | {:ok, socket} = :gen_udp.open 0 66 | host = host |> to_char_list 67 | {:udp, host, port, socket} 68 | {:tcp, host, port} -> 69 | host = host |> to_char_list 70 | {:ok, tcp_client} = TCPClient.start_link(host, port) 71 | {:tcp, tcp_client} 72 | end 73 | %{metadata: metadata, level: level, output: output} 74 | end 75 | 76 | defp log_event(level, msg, ts, md, %{metadata: metadata, output: :console}) do 77 | IO.puts event_json(level, msg, ts, md, metadata) 78 | end 79 | 80 | defp log_event(level, msg, ts, md, %{metadata: metadata, output: {:udp, host, port, socket}}) do 81 | json = event_json(level, msg, ts, md, metadata) 82 | :gen_udp.send socket, host, port, [json] 83 | end 84 | 85 | defp log_event(level, msg, ts, md, %{metadata: metadata, output: {:tcp, client}}) do 86 | json = event_json(level, msg, ts, md, metadata) 87 | TCPClient.log_msg client, json 88 | end 89 | 90 | defp event_json(level, msg, _ts, md, metadata) do 91 | pid_str = :io_lib.fwrite('~p', [md[:pid]]) |> to_string 92 | JSON.encode! %{level: level, message: msg, pid: pid_str, module: md[:module], function: md[:function], line: md[:line], metadata: metadata} 93 | end 94 | end 95 | -------------------------------------------------------------------------------- /lib/json_logger/tcp_client.ex: -------------------------------------------------------------------------------- 1 | defmodule Logger.Backends.JSON.TCPClient do 2 | use GenServer 3 | 4 | @reconnect_timeout 5000 5 | @tcp_options [:binary, {:packet, 0}, {:nodelay, true}, {:keepalive, true}] 6 | 7 | def start_link(host, port) do 8 | GenServer.start_link __MODULE__, {host, port}, [] 9 | end 10 | 11 | def log_msg(client, msg) do 12 | GenServer.cast client, {:send_log, msg} 13 | end 14 | 15 | def stop(client) do 16 | GenServer.cast client, :stop 17 | end 18 | 19 | def init({host, port}) do 20 | {:ok, %{host: host, port: port, socket: nil, timeout: 0, stash: []}, 0} 21 | end 22 | 23 | def handle_cast({:send_log, msg}, %{socket: nil, timeout_start: timeout_start, stash: stash} = state) do 24 | stash = [msg | stash] 25 | {:noreply, %{state | stash: stash}, timeout_left(timeout_start)} 26 | end 27 | 28 | def handle_cast({:send_log, msg}, %{socket: socket, stash: stash} = state) do 29 | msg_list = 30 | (["", msg] ++ stash) 31 | |> Enum.reverse 32 | |> Enum.intersperse("\n") 33 | case :gen_tcp.send(socket, msg_list) do 34 | :ok -> 35 | {:noreply, state} 36 | {:error, _reason} -> 37 | # TODO: Error handling 38 | {:noreply, state} 39 | end 40 | end 41 | 42 | def handle_cast(:reconnect, %{host: host, port: port} = state) do 43 | case :gen_tcp.connect(host, port, @tcp_options) do 44 | {:ok, socket} -> 45 | {:noreply, %{state | socket: socket}} 46 | {:error, _} -> 47 | state = %{state | timeout_start: :os.system_time} 48 | {:noreply, state, @reconnect_timeout} 49 | end 50 | end 51 | 52 | def handle_cast(:stop, _state) do 53 | {:stop, :normal} 54 | end 55 | 56 | def handle_info(:timeout, %{socket: nil} = state) do 57 | GenServer.cast self(), :reconnect 58 | {:noreply, state} 59 | end 60 | 61 | def handle_info({:tcp_closed, socket}, %{socket: socket} = state) do 62 | {:noreply, %{state | socket: nil}, 0} 63 | end 64 | 65 | def terminate(_reason, %{socket: socket}) do 66 | :gen_tcp.close socket 67 | :ok 68 | end 69 | 70 | defp timeout_left(timeout_start) do 71 | case ((timeout_start + @reconnect_timeout) - :os.system_time) do 72 | n when n < 0 -> 0 73 | n -> n 74 | end 75 | end 76 | 77 | end 78 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Logger.Backends.JSON.Mixfile do 2 | use Mix.Project 3 | 4 | def project do 5 | [app: :json_logger, 6 | version: "0.6.0", 7 | elixir: ">= 1.0.0", 8 | deps: deps, 9 | description: "A simple library for logging with JSON, best suited with Logstash.", 10 | package: package, 11 | source_url: "https://github.com/LeeroyDing/json_logger"] 12 | end 13 | 14 | def application, do: [] 15 | 16 | defp deps do 17 | [{:json, "~> 0.3.2"}] 18 | end 19 | 20 | def package do 21 | [ 22 | maintainers: ["Leeroy Ding"], 23 | licenses: ["Apache License 2.0"], 24 | links: %{"GitHub" => "https://github.com/LeeroyDing/json_logger"} 25 | ] 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{"json": {:hex, :json, "0.3.2"}, 2 | "timex": {:hex, :timex, "0.13.4"}} 3 | -------------------------------------------------------------------------------- /test/json_logger_tcp_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Logger.Backends.JSON.TCPTest do 2 | use ExUnit.Case, async: false 3 | require Logger 4 | 5 | @backend {Logger.Backends.JSON, :test} 6 | 7 | @message "Yo" 8 | @metadata "Very important data" 9 | @level :debug 10 | 11 | setup_all do 12 | {:ok, server} = :gen_tcp.listen 0, [:binary, {:active, false}, {:packet, 0}, {:reuseaddr, true}] 13 | {:ok, port} = :inet.port server 14 | config [level: @level, metadata: @metadata, output: {:tcp, "localhost", port}] 15 | on_exit fn -> 16 | :gen_tcp.close(server) 17 | end 18 | {:ok, server: server} 19 | end 20 | 21 | test "sends debug message via TCP", %{server: server} do 22 | Logger.debug @message 23 | assert {:ok, client} = :gen_tcp.accept(server, 500) 24 | assert {:ok, message} = :gen_tcp.recv(client, 0, 500) 25 | assert :ok = :gen_tcp.close(client) 26 | assert {:ok, result} = JSON.decode(message) 27 | assert result["level"] == to_string(@level) 28 | assert result["message"] == @message 29 | assert result["metadata"] == @metadata 30 | end 31 | 32 | defp config(opts) do 33 | Logger.configure_backend(@backend, opts) 34 | end 35 | 36 | end 37 | -------------------------------------------------------------------------------- /test/json_logger_udp_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Logger.Backends.JSON.UDPTest do 2 | use ExUnit.Case, async: false 3 | require Logger 4 | 5 | @backend {Logger.Backends.JSON, :test} 6 | 7 | @message "Yo" 8 | @metadata "Very important data" 9 | @level :debug 10 | 11 | setup_all do 12 | {:ok, server} = :gen_udp.open 0, [:binary, {:active, false}] 13 | {:ok, port} = :inet.port(server) 14 | config [level: @level, metadata: @metadata, output: {:udp, "localhost", port}] 15 | on_exit fn -> 16 | :gen_udp.close(server) 17 | end 18 | {:ok, server: server} 19 | end 20 | 21 | test "sends debug message via UDP", %{server: server}do 22 | Logger.debug @message 23 | assert {:ok, {_ip, _port, message}} = :gen_udp.recv(server, 0, 500) 24 | assert {:ok, result} = JSON.decode(message) 25 | assert result["level"] == to_string(@level) 26 | assert result["message"] == @message 27 | assert result["metadata"] == @metadata 28 | end 29 | 30 | test "can change metadata", %{server: server} do 31 | new_metadata = "New metadata" 32 | config [metadata: new_metadata] 33 | Logger.debug @message 34 | assert {:ok, {_ip, _port, message}} = :gen_udp.recv(server, 0, 500) 35 | assert {:ok, result} = JSON.decode(message) 36 | assert result["level"] == to_string(@level) 37 | assert result["message"] == @message 38 | assert result["metadata"] == new_metadata 39 | config [metadata: @metadata] 40 | end 41 | 42 | test "can use info level", %{server: server} do 43 | config [level: :info] 44 | Logger.debug @message 45 | assert {:error, :timeout} = :gen_udp.recv(server, 0, 500) 46 | Logger.info @message 47 | assert {:ok, {_ip, _port, message}} = :gen_udp.recv(server, 0, 500) 48 | assert {:ok, result} = JSON.decode(message) 49 | assert result["level"] == "info" 50 | assert result["message"] == @message 51 | assert result["metadata"] == @metadata 52 | config [level: @level] 53 | end 54 | 55 | defp config(opts) do 56 | Logger.configure_backend(@backend, opts) 57 | end 58 | 59 | end 60 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | require Logger 2 | 3 | :application.start :logger 4 | Logger.remove_backend :console 5 | Logger.add_backend {Logger.Backends.JSON, :test} 6 | 7 | ExUnit.start() 8 | --------------------------------------------------------------------------------