Implement an Elixir macro using that injects a standard set of logging functions and a…
- User
Implement an Elixir macro
__using__that injects a standard set of logging functions and a dynamicchild_specinto the calling module. Assistant
The user wants an Elixir macro that injects specific functionality into a module when
use MyModuleis called. Specifically, the user asked for:- Injection of a "standard set of logging functions".
- Injection of a "dynamic
child_spec".
I need to design a module (let's call it
MyLibrary) that defines the__using__macro.1. The
__using__Macro Structure The basic structure looks like this:defmodule MyLibrary do defmacro __using__(opts) do quote do # ... code to inject ... end end end2. Logging Functions The user requested a "standard set of logging functions". This usually implies wrappers around
Logger(likeinfo,error,debug) or perhaps functions that format logs specifically for the module. Let's stick to a common use case: injecting functions that prefix the log with the module name or provide a consistent interface. However, simply importingLoggerisn't really "injecting functions". The user specifically said "injects... functions". Let's define some helper functions:log_info(message)log_error(message)log_debug(message)
Inside these functions, we should probably use Elixir's
Loggermodule. To make it "dynamic" or context-aware, we can capture the__MODULE__of the caller inside the macro.3. Dynamic
child_specThe user requested a "dynamicchild_spec". This implies the module using this macro is likely anGenServer,Supervisor, orAgent. Achild_specfunction usually returns a map or a tuple%{id: ..., start: ..., ...}. To make it dynamic, we usually want the macro to generate achild_spec/1function that accepts options (usuallyinit_arg) and merges them with defaults. Standarduse GenServergenerates achild_spec/1. If I implement a customchild_specinjection, I should probably allow the user to override theidorstartdefinition, or just provide a standard boilerplate. Let's implement achild_spec/1function that:- Uses the module name as the ID.
- Defines the start function as
{__MODULE__, :start_link, [arg]}. - Allows overrides via keyword lists passed to
use.
Refining the "Dynamic" aspect: Maybe the user means "Dynamic" as in the
child_specallows runtime configuration, or perhaps simply that it exists without the user writing it manually. Let's assume the latter: generate a standardchild_specthat allows passing options to thestart_linkfunction.Implementation Details:
-
The Logging functions:
def log_info(msg), do: Logger.info("[#{__MODULE__}] #{msg}") def log_error(msg), do: Logger.error("[#{__MODULE__}] #{msg}") def log_warn(msg), do: Logger.warn("[#{__MODULE__}] #{msg}")Wait, if I define these inside
quote,__MODULE__refers to the caller's module (the one using the macro). That's good. -
The
child_spec:def child_spec(opts) do %{ id: __MODULE__, start: {__MODULE__, :start_link, [opts]}, shutdown: 5000, restart: :permanent, type: :worker } endTo make it slightly more robust, I should allow the
usecall to take options that modify this spec. e.g.,use MyMacro, restart: :transient.
Putting it together in code:
defmodule MyMacro do defmacro __using__(opts) do quote do require Logger # Inject Logging Functions def log_info(message), do: Logger.info("[#{__MODULE__}] #{message}") def log_error(message), do: Logger.error("[#{__MODULE__}] #{message}") def log_debug(message), do: Logger.debug("[#{__MODULE__}] #{message}") # Inject Dynamic child_spec # We use the opts passed to 'use' to set defaults, and allow runtime opts to override them? # Standard behavior is child_spec(init_arg). # Let's keep it simple but functional. def child_spec(init_arg) do # Default spec default_spec = %{ id: __MODULE__, start: {__MODULE__, :start_link, [init_arg]}, type: :worker } # Allow overriding via compile-time opts from 'use MyMacro, ...' # This requires `unquote(opts)` to be accessible. # But usually child_spec/1 takes the argument passed to the supervisor. # Let's stick to generating a standard function definition. # If the user wants to customize, they can define their own child_spec and it will override this one # (though in Elixir, defining a function in the module overrides the macro injection if defined after? # Actually, usually `use` is at the top, so user definitions come after. # But if the macro defines `def child_spec`, and the user defines `def child_spec`, the compiler will complain about ambiguity or redefine depending on context. # Actually, in Elixir, if you define a function in `quote` and the user defines the same function in their module body, it results in a "function clause already defined" error if they are identical, or multiple clauses. # To be safe, we should check if the user provided options in `use` to disable this, or structure it so it's easy to override. # Let's provide a `defoverridable` approach? No, child_spec logic is usually specific. # Let's just inject the function. # To make it "Dynamic" based on the `use` options: # Example: `use MyMacro, type: :supervisor` unquote(opts) # this is available here. %{ id: __MODULE__, start: {__MODULE__, :start_link, [init_arg]}, type: unquote(Keyword.get(opts, :type, :worker)), restart: unquote(Keyword.get(opts, :restart, :permanent)) } end end end endRefining the Logic for
child_specwithMacro.escape? No, simpleunquoteis enough for compile-time constants.Wait, I should be careful about
child_specconflicts. If the module callsuse GenServer,GenServeralso injects achild_spec. If the user does:defmodule MyWorker do use GenServer use MyMacro ... endGenServer.__using__injectschild_spec.MyMacro.__using__injectschild_spec. This will fail to compile (function already defined). To avoid this, standard practice is often to provide a function like__my_macro_child_spec__or advise the user not to useuse GenServerifMyMacrohandles it, OR make the injectedchild_specrobust. However, the prompt asks specifically to injectchild_spec. I will implement it assuming the user relies on this macro for the child spec, or I should generate it such that it merges. But typically, a customusingmacro replaces the need foruse GenServer's default injection if you are providing achild_spec. Let's add a check orunless defined?logic? Macros can't easily check if a function is already defined in the user's code (which comes after the macro expansion usually, or strictly speaking, the macro is expanded first, then the module body is evaluated). Actually,Module.defines?/3might work in the macro context if we pass the environment, butquoteblocks are just AST. Let's stick to the direct injection. If it conflicts, the user controls their imports. I will note this in the explanation.Let's polish the Logging functions. Instead of just
log_info, maybe injectinfo(shorthand)? No, that might conflict withKernel.log_infois safer.The "Dynamic" part of
child_specOften "dynamic child_spec" implies that the ID is unique or the start args vary. Let's implement it so thechild_specmerges the options passed touse(compile time) with the arguments passed tochild_spec/1(runtime).Example usage goal:
defmodule MyServer do use MyMacro, restart: :transient def start_link(opts), do: # ... endThis should generate
child_spec/1.Final Code Structure Plan:
- Define module
StandardBehavior. defmacro __using__(opts).quoteblock.require Logger.- Define
log_info/1,log_error/1,log_debug/1. These will format the string including the caller module name. - Define
child_spec/1. It should takeinit_arg. It should generate the map. It should look atunquote(opts)for defaults like:restartor:shutdown.
Wait, handling
init_arginchild_spec: Standard pattern:child_spec(arg)->%{start: {Mod, :start_link, [arg]}}. This is standard.One edge case: If the user does
use MyMacro, they likely aren't doinguse GenServer(ifMyMacrois a framework wrapper). If they do both, they have to handle the conflict. However, to make the code copy-pasteable and robust, I will simply provide the implementation.Let's add a small feature: allow the user to disable
child_specgeneration via options, just in case. e.g.use MyMacro, child_spec: false. This is "Good Practice".Summary of Implementation:
defmodule StandardBehavior do defmacro __using__(opts) do quote do require Logger # 1. Logging Functions def log_info(msg), do: Logger.info("[#{__MODULE__}] #{msg}") def log_error(msg), do: Logger.error("[#{__MODULE__}] #{msg}") def log_debug(msg), do: Logger.debug("[#{__MODULE__}] #{msg}") # 2. Dynamic Child Spec if unquote(Keyword.get(opts, :child_spec, true)) do def child_spec(init_arg) do %{ id: __MODULE__, start: {__MODULE__, :start_link, [init_arg]}, # Merge compile-time opts (from `use`) with defaults type: unquote(Keyword.get(opts, :type, :worker)), restart: unquote(Keyword.get(opts, :restart, :permanent)), shutdown: unquote(Keyword.get(opts, :shutdown, 5000)) } end end end end endWait,
ifinsidequoteblock works at compile time of the caller. That's correct.unquote(...)is evaluated when the macro is called (compile time of caller). SoKeyword.get(opts, :child_spec, true)is evaluated during compilation.This looks correct and answers the prompt.
Self-Correction / Refinement: The prompt asks for "Implement an Elixir macro". I should provide the module code and an example of how to use it.
Let's refine the
log_infoimplementation.Logger.info/2accepts a metadata list or just a string. MaybeLogger.info(fn -> "[#{__MODULE__}] #{msg}" end)is better for performance (lazy evaluation), though for a simple example, direct string interpolation is fine. I'll stick to the simple version for readability unless I want to show off best practices. Let's use the anonymous function version for correctness/laziness? No,msgmight not be a string, might needinspect. Let's keep it simple:Logger.info("#{__MODULE__}: #{inspect(msg)}"). Actually, standard logging usually just takes the message.Let's stick to the prompt's request: "standard set of logging functions".
log_info/1,log_warn/1,log_error/1.Regarding
child_spec: Ifinit_argis a keyword list,start_linkexpects a keyword list. Ifinit_argis a map,start_linkexpects a map. The standardchild_specjust passesinit_argas is.Final check on "Dynamic"
child_spec. Maybe it implies that thechild_specmerges arguments? E.g.def child_spec(arg) do %{ id: {__MODULE__, arg[:name]}, # Dynamic ID based on args? ... } endThe prompt is slightly ambiguous, but "injects a... dynamic
child_spec" usually refers to generating the function based on the__using__options. I will stick to the interpretation that thechild_specis generated dynamically based on compile-time options (like:restartstrategy) passed touse.Let's write the solution.
Structure:
StandardInjectormodule.- The
__using__macro. - An example module using it.
Here is the implementation of the
__using__macro. This module, whenused, will inject logging helpers and a configurablechild_specinto the calling module.
The Implementation
defmodule StandardBehavior do @moduledoc """ Provides a `__using__` macro to inject standard logging functions and a dynamic `child_spec` into the calling module. """ defmacro __using__(opts) do quote do require Logger # ------------------------------------------------------------------- # 1. Inject Standard Logging Functions # ------------------------------------------------------------------- @doc "Logs an info message prefixed with the module name." def log_info(message) do Logger.info("[#{__MODULE__}] #{message}") end @doc "Logs an error message prefixed with the module name." def log_error(message) do Logger.error("[#{__MODULE__}] #{message}") end @doc "Logs a debug message prefixed with the module name." def log_debug(message) do Logger.debug("[#{__MODULE__}] #{message}") end # ------------------------------------------------------------------- # 2. Inject Dynamic Child Spec # ------------------------------------------------------------------- # We only generate the child_spec if the user hasn't disabled it # (e.g., via `use StandardBehavior, child_spec: false`) if unquote(Keyword.get(opts, :child_spec, true)) do @doc """ Returns a child specification for a supervisor. Allows the start function to be called with arguments provided at runtime (init_arg) or compile time (via `use` options). """ def child_spec(init_arg \\ []) do # Default values can be overridden in the `use` options # (e.g., `use StandardBehavior, id: :my_worker, restart: :transient`) default_spec = %{ id: __MODULE__, start: {__MODULE__, :start_link, [init_arg]}, restart: :permanent, type: :worker } # Merge compile-time opts on top of defaults # Note: We exclude :child_spec to prevent infinite loops in logic compile_opts = unquote(opts) |> Keyword.delete(:child_spec) Supervisor.child_spec(default_spec, compile_opts) end end end end endHow to Use It
You can now use this macro in other modules to automatically equip them with the logging functions and the supervisor boilerplate.
defmodule MyWorker do # 1. Use the macro. You can pass options to customize the child_spec. use StandardBehavior, id: :my_custom_id, restart: :transient, # You can even disable child_spec generation if you want to define your own manually # child_spec: false def start_link(opts) do # 2. The injected logging functions are available immediately log_info("Starting worker with options: #{inspect(opts)}") # ... implementation logic ... {:ok, self()} end end # Testing the injection: # 1. Logging MyWorker.log_info("Hello World") # Output: [info] [MyWorker] Hello World # 2. Child Spec # This generates the map based on the dynamic macro logic IO.inspect(MyWorker.child_spec([some: :arg]), label: "Child Spec") # Output: # Child Spec: %{ # id: :my_custom_id, <-- Overridden via `use` # restart: :transient, <-- Overridden via `use` # start: {MyWorker, :start_link, [[some: :arg]]}, # type: :worker # }Explanation of Key Concepts
quote do ... end: This block returns the Abstract Syntax Tree (AST) of the code we want to inject. Whenuse StandardBehavioris called, this code is essentially copy-pasted into the calling module (MyWorker).unquote(opts): We need to access the arguments passed touse(likerestart: :transient) inside thequoteblock.unquoteinjects the value of the outer variableoptsinto the inner AST.__MODULE__: Inside thequote,__MODULE__refers to the calling module (e.g.,MyWorker), not the macro module itself. This ensures the logs andchild_specreference the correct name.Supervisor.child_spec/2: Instead of manually building the Map, we leverage Elixir's built-inchild_spechelper. It handles the merging of defaults with custom overrides (like:idor:shutdown) intelligently.